尝试对字符串向量进行排序时 C++ 程序崩溃

C++ program crashes when trying to sort a vector of strings

我试图在 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;
}

传递给排序的比较器必须满足named requirement Compare:

Establishes strict weak ordering relation with the following properties

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