C++;程序在尝试对字符串向量排序时崩溃 我试图在C++中排序字符串数组,但是我得到以下错误信息: terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid

C++;程序在尝试对字符串向量排序时崩溃 我试图在C++中排序字符串数组,但是我得到以下错误信息: terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid,c++,string,sorting,vector,sigabrt,C++,String,Sorting,Vector,Sigabrt,传递给排序的比较器必须满足以下条件: 建立严格的弱序关系 性质 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的先决条件,您的代码具有未定义的行为。std::sort的比较器要求严格的弱排序。把它想象成“少于”。在您

传递给排序的比较器必须满足以下条件:

建立严格的弱序关系 性质

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
的先决条件,您的代码具有未定义的行为。

std::sort的比较器要求严格的弱排序。把它想象成“少于”。在您的设置中,
“a”
是真的,这没有任何意义。@MikeVine所说的,请尝试
返回s1.size()。旁注:你的比较器有点贵。使其
bool comp(const string&s1,const string&s2)
不必每次复制字符串。通常,如果有
if(condition){return true;}或者{return false;}
可以直接替换为
retur condition。引发异常的行为很有趣。只有将大于或等于的语义与按值参数进行比较时,才会发生这种情况。通过引用传递或与小于进行比较不会产生此()@humancompiler未定义行为:-)
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