简体   繁体   English

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

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

I'm trying to sort an array of strings in C++, but I am getting the following error message:我正在尝试在 C++ 中对字符串数组进行排序,但收到以下错误消息:

terminate called after throwing an instance of 'std::logic_error'  
  what():  basic_string::_M_construct null not valid

The following program causes the previous error.以下程序会导致上一个错误。 I got the error when v has 17 elements, but everything works fine when v has less elements.我得到的错误时, v有17个元素,但一切正常时, v具有更少的元件。

Could someone point me out what is the problem?有人能指出我有什么问题吗? I'm using gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04)我正在使用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;
}

The comparator you pass to sort must satisfy the named requirement Compare :您传递给 sort 的比较器必须满足命名要求 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

With your comparator: comp(a,a) == true .使用比较器: comp(a,a) == true As you do not fullfill the preconditions of std::sort your code has undefined behavior.由于您没有满足std::sort的先决条件,因此您的代码具有未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM