尝试对字符串向量进行排序时,C ++程序崩溃 [英] C++ program crashes when trying to sort a vector of strings

查看:86
本文介绍了尝试对字符串向量进行排序时,C ++程序崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对C ++中的字符串数组进行排序,但是却收到以下错误消息:

I'm trying to sort an array of strings in C++, but I am getting the following error message:


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

以下程序导致上一个错误.当 v 具有17个元素时出现错误,但是当 v 具有较少元素时,一切正常.

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.

有人可以指出我的问题吗?我正在使用 gcc版本7.5.0(Ubuntu 7.5.0-3ubuntu1〜18.04)

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;
}

推荐答案

传递给您的比较器必须满足命名需求比较:

The comparator you pass to sort must satisfy the 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 的前提条件,因此您的代码具有未定义的行为.

With your comparator: comp(a,a) == true. As you do not fullfill the preconditions of std::sort your code has undefined behavior.

这篇关于尝试对字符串向量进行排序时,C ++程序崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆