简体   繁体   中英

Why Vector won't sort?

I was solving a problem on an oj. But suddenly I found that vector<char*> would not sort on my purpose. What am I doing wrong? If anyone could make that problem clear to me... The problem description is simple, you just need to take the word from the input file and sort it. Here's what I have done, But it won't sort:

vector<char*>V;
char str[501][201];
int l=0;
char str1[]= {'~','.','\n','\r',' ','!','@','#','$','%','^','&','*','(',')','+','-','_','=','{','}','[',']',':',';','"','<','>','?','/','|'};
while(gets(str[l++]))
{

    for(int i=0; str[l-1][i]; i++)
    {
        if(str[l-1][i]>='A' && str[l-1][i]<='Z')str[l-1][i]=str[l-1][i]-'A'+'a';
    }
    char *pch;
    pch=strtok(str[l-1],str1);
    while(pch!=NULL)
    {
        // printf("%s\n",pch);
        V.push_back(pch);
        pch=strtok(NULL,str1);
    }
}

sort(V.begin(),V.end());

for(vector<char*>::iterator it=V.begin(); it!=V.end(); it++)
    cout<<*it<<endl;

When applied to char * , the < operator (which sort() defaults to) orders by pointer values, not lexicographically. You need to supply a custom comparator. In C++11, this is fairly easy:

sort(V.begin(), V.end(),
     [](char const * a, char const * b) { return strcmp(a, b) < 0; });

If your compiler doesn't support lambdas, you'll have to declare an appropriate comparator outside the function:

struct CStringLess {
    bool operator()(char const * a, char const * b) const {
        return strcmp(a, b) < 0;
    }
};
⋮
sort(V.begin(), V.end(), CStringLess());

Another problem you have is that str1 isn't null terminated, as strtok() requires. But rather than adding it to the end, redefine it as a C string, which is more concise and gives you the null-terminator for free:

char * str1 = "~.\n\r !@#$%^&*()+-_={}[]:;\"<>?/|";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM