hdu1862结构体中string成员之内存泄漏

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
using namespace std;

struct stu
{
    string num,name;
    int grade;
} a[100100];

bool cmp1(stu a,stu b)
{
    return a.num<b.num;
}
bool cmp2(stu a,stu b)
{
    if(a.name==b.name)
    return a.num<=b.num;
    return a.name<=b.name;
}
bool cmp3(stu a,stu b)
{
    if(a.grade==b.grade)
    return a.num<=b.num;
    return a.grade<=b.grade;
}

int main()
{
    int n,c;
    int cas=1;
    while(scanf("%d%d",&n,&c)!=-1,n)
    {
        //memset(a,0,sizeof(a));有这个就RE
        //每次memset,把string维护的指针弄没了。所以找不到之前的数据了,就导致内存泄露
        for(int i=0; i<n; i++)
        {
            cin>>a[i].num>>a[i].name>>a[i].grade;
        }
        if(c==1)
            sort(a,a+n,cmp1);
        if(c==2)
            sort(a,a+n,cmp2);
        if(c==3)
            sort(a,a+n,cmp3);
        printf("Case %d:\n",cas++);
        for(int i=0; i<n; i++)
            cout<<a[i].num<<" "<<a[i].name<<" "<<a[i].grade<<endl;
    }
    return 0;
}

用char[]就没事了

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

struct stu
{
    char name[10],num[10];
    int grade;
} a[100100];

bool cmp1(stu a,stu b)
{
    return strcmp(a.num,b.num)<1;
}
bool cmp2(stu a,stu b)
{
    if(strcmp(a.name,b.name)==0)
    return strcmp(a.num,b.num)<1;
    return strcmp(a.name,b.name)<1;
}
bool cmp3(stu a,stu b)
{
    if(a.grade==b.grade)
    return strcmp(a.num,b.num)<1;
    return a.grade<=b.grade;
}

int main()
{
    int n,c;
    int cas=1;
    while(scanf("%d%d",&n,&c)!=-1,n)
    {
        memset(a,0,sizeof(a));
        for(int i=0; i<n; i++)
        {
            cin>>a[i].num>>a[i].name>>a[i].grade;
        }
        if(c==1)
            sort(a,a+n,cmp1);
        if(c==2)
            sort(a,a+n,cmp2);
        if(c==3)
            sort(a,a+n,cmp3);
        printf("Case %d:\n",cas++);
        for(int i=0; i<n; i++)
            cout<<a[i].num<<" "<<a[i].name<<" "<<a[i].grade<<endl;
    }
    return 0;
}
    原文作者:B树
    原文地址: https://blog.csdn.net/aonaigayiximasi/article/details/79234342
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞