为什么下面的代码给出 'std::logic_error' what(): basic_string::_M_construct null 无效?



当我使用for循环运行函数sort_string,但不使用简单的关系运算符来比较两个字符串时,我得到std::logic_error'what((:basic_string::_M_construct null无效。该程序从给定数字的向量中构造最大的数字。对于小输入,它可以正常工作,但对于大输入则不行。我提供了以下输入。

#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 10 6 3 3 3 8 4 1 10 8 4 1 3 2 2 6 1 5 2 9 8 5 10 8 7 6 6 6 6 8 8 9 9 10 3 7 7 7 7 1 7 7 7 4 7 7 8 1 7 7 4 9 9 9 9 5

问题是由引起的

return true;

在CCD_ 1中。它需要

return false;

当您到达该行时,xy等于yx。因此,yx < xyfalse,而不是true

线路

return xy >= yx;

有效,因为该线路与相同

return yx < xy;

您的代码只需将for loop之外的return true更改为return false即可工作。然而,我不明白为什么当你可以简单地进行时,你会把这个代码复杂化SO

bool sort_string(const std::string& x, const std::string& y)
{
return x > y;
}

或者甚至将其实现为lambda。

最新更新