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

C++ program not working for large input (logic_error, _M_construct null not valid)

我正在尝试实现薪水最大化问题。就像给定两个数字 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

如何解决这个问题?我阅读了一些可能的解决方案,其中涉及我无法理解的 NULL 指针。

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

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

相关问题:Why will std::sort crash if the comparison function is not as operator <?