gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:50:08 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com