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

标签 c++ string sorting vector sigabrt

我正在尝试在 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.

Could someone point me out what is the problem? I'm using gcc version 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;
}

最佳答案

您传递给 sort 的比较器必须满足 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 的先决条件您的代码具有未定义的行为。

关于尝试对字符串 vector 进行排序时,C++ 程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64014782/

相关文章:

javascript - 按数据属性对列表进行排序

python - 首先按第一列排序二维列表,然后按第二列排序

c++ - 关于忽略字符顺序的字符串哈希函数的建议

c++ - 在基于范围的 for 循环中,引用是否比小类型的拷贝更有效?

c++ - 使 C++ 库可用于 .Net

python - 查找 HDF5 数据集中的唯一列

java - 映射 : expected org. apache.hadoop.io.Text 中的键类型不匹配,收到 org.apache.hadoop.io.IntWritable

c - 在 C 中检查给定字符串是否为回文的有效方法

java - 获取第二个数组中特定行或列中的最小元素

C++ std::stringstream 操作优化