简体   繁体   中英

c++ STL sort with extra parameter 'invalid operator <'

I am trying to sort a not so small vector of strings with self-defined comparing rule which is here:

  bool lexGraph(string const &str1, string const &str2)
{
    string::const_iterator i1 = str1.begin(), i2 = str2.begin();

    while((i1 < str1.end()) && (i2 < str2.end()))
    {
        if(*i1 == ' ')
        {
            i1++;
            continue;
        }
        if(*i2 == ' ')
        {
            i2++;
            continue;
        }
        if(toupper(*i1) < toupper(*i2))
        {
            return true;
        }
        if(toupper(*i1) > toupper(*i2))
        {
            return false;
        }
        i1++, i2++;
    }
    return (str1.length() <= str2.length());
}

I use it in this loop:

vector<string> subset;
    ifstream fin(input);
    ofstream fout(output);
    string buff;
    for(long i = 0; i < 241; i++) 
    {
        getline(fin,buff);
        buff += '\n';
        subset.push_back(buff);

    }
sort(subset.begin(), subset.end(),lexGraph);

I found out that the overflow error occurs with vectors larger than 240. I found that this number can even become smaller if I use a smaller file. Also, strings are never really big. If I cut my function down to

bool lexGraph(string const &str1, string const &str2)
{
    return (str1.length() <= str2.length());
}

the error still occurs. But it doesnt when I use STL sort without an extra parameter.

So, I cant figure where the leak is and I hope for some hint here.

You need a strict-weak ordering. Your function for ordering must return false when called with equal strings. If you compare with <= , it doesn't work. BTW: I believe that some standard library implementations have a diagnostic mode that could have caught this error for you. Use this, as there are enough ropes in C++ that you can shoot yourself in the foot with.

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