【发布时间】:2020-09-01 03:01:21
【问题描述】:
当我使用 for 循环而不是使用简单的关系运算符来比较两个字符串时,我得到 std::logic_error' what(): basic_string::_M_construct null not valid 当我运行函数 sort_string 时。 该程序从给定数字的向量构造最大的数字。对于小输入,它工作正常,但不适用于大输入。我在下面提供了输入。
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
bool sort_string(std::string x, std::string y) {
std::string xy = x.append(y);
std::string yx = y.append(x);
// For loop below, to calculate larger string gives "terminate called after throwing
// an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid"
// Just comment the for loop and uncomment the last return statement to see
//-------------------------------------------------------------------------------------------------------
for (int i = 0; i < xy.size(); i++) {
if (xy.at(i) > yx.at(i)) return true;
if (yx.at(i) > xy.at(i)) return false;
}
return true;
//-------------------------------------------------------------------------------------------------------
/*
This runs perfectly fine
*/
//return xy>=yx;
}
int main() {
int n;
std::cin >> n;
std::vector<std::string> arr(n);
for (int i = 0; i < n; i++) {
std::cin>>arr[i];
}
std::sort(arr.begin(), arr.end(), sort_string);
for (int i = 0; i < n; i++) {
std::cout << arr[i];
}
std::cout << std::endl;
}
说明: 使用 g++ -std=c++14 运行
输入:
100
2 8 2 3 6 4 1 1 10 6 3 3 6 1 3 8 4 6 1 10 8 4 10 4 1 3 2 3 2 6 1 5 2 9 8 5 10 8 7 9 6 4 2 6 3 8 8 9 8 2 9 10 3 10 7 5 7 1 7 5 1 4 7 6 1 10 5 4 8 4 2 7 8 1 1 7 4 1 1 9 8 6 5 9 9 3 7 6 3 10 8 10 7 2 5 1 1 9 9 5
【问题讨论】:
-
我得到的崩溃表明您的比较不遵守严格的弱排序。
-
谢谢!我不知道 sort 的比较函数中的严格弱排序。我现在明白了。还有一个疑问请参阅@R Sahu 评论部分。
标签: c++ debugging runtime-error c++14