C++程序不适用于大输入(logic_error,_M_construct null无效)



我正在尝试实现薪酬最大化问题。就像如果给我们两个数字221,那么得到的数字应该是221而不是212。我实现了代码,它对小输入非常有效。该代码使用带有简单比较器功能的C++std::sort。对于像100这样的大输入,它会失败并给出以下错误。

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

这是我的代码:

#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
using std::max;

bool comp(const string &a, const string &b) {
string combo1 = a+b;
string combo2 = b+a;
return combo1>=combo2;
}
string largest_number(vector<string> a) {
std::sort(a.begin(), a.end(), comp);
string result = "";
for (int i=0; i< a.size(); i++) {
result = result + a[i];
}
return result;
}
int main() {
int n;
std::cin >> n;
vector<string> a(n);
for (size_t i = 0; i < a.size(); i++) {
std::cin >> a[i];
}
std::cout << largest_number(a);
}

对于以下输入,它给出错误。

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

我该如何解决此问题?我读了一些可能的解决方案,其中有一些关于空指针的内容,我无法理解。

您的比较器功能不符合要求。也就是说,它没有定义严格弱序。有关更多详细信息,请参阅文档。

例如,comp(s,s)必须是false,而在代码中,使用相同的参数调用comp总是会产生true。基本上,在定义比较器时,您可能不会使用>=<=

相关问题:如果比较函数不是运算符<,为什么std::sort会崩溃;?

最新更新