Reputation: 21
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.
Upvotes: 1
Views: 986
Reputation: 17415
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.
Upvotes: 3