问题描述
我正在尝试对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" };
sort(v.begin(),v.end(),comp);
return 0;
}
解决方法
传递给您的比较器必须满足named requirement Compare:
与以下项建立严格的弱排序关系 属性
For all a,comp(a,a)==false If comp(a,b)==true then comp(b,a)==false if comp(a,b)==true and comp(b,c)==true then comp(a,c)==true
使用您的比较器:comp(a,a) == true
。由于您没有满足std::sort
的前提条件,因此您的代码具有未定义的行为。