我正在尝试在C++中对字符串数组进行排序,但是出现了以下错误信息:
terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid
下面的程序引起了上述错误。当v
有17个元素时,我遇到了这个错误,但是当v
的元素较少时,一切正常。
有人能指出问题所在吗?我正在使用gcc版本7.5.0(Ubuntu 7.5.0-3ubuntu1〜18.04)
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
bool comp (string s1, string s2) {
if (s1.size() < s2.size())
return false;
else
return true;
}
int main () {
vector<string> v = { "a", "a", "a", "a",
"a", "a", "a", "a",
"a", "a", "a", "a",
"a", "a", "a", "a",
"a" };
sort(v.begin(), v.end(), comp);
return 0;
}
std::sort
的比较器要求具有“严格弱序”。可以将其看作是“小于”。在您的设置中,“a”< “a”的结果是 _true_,这是不合理的。 - Mike Vinereturn s1.size() < s2.size();
。顺便说一句:你的比较函数有点昂贵。将它改为bool comp (const string& s1, const string& s2)
,这样就不用每次都复制字符串了。 - Ted Lyngmoif (condition) { return true; } else { return false; }
这样的代码,可以直接替换成return condition;
。 - Some programmer dude