1
votes

I encounter the error below when solving the leetcode problem https://leetcode.com/problems/largest-number/.

terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::_M_create

So I run a similar code down bellow locally and it gives me segmentation fault. (Btw, it can run without any issues when the vector size is smaller, like 10). I already read the solutions, so I know there is a better way to do solve this leetcode problem. I just wanna know the nuance of this segmentation fault.

#include <bits/stdc++.h>
using namespace std;

int main() {
  vector<string> arr(100, "0");

  sort(arr.begin(), arr.end(), [](string &x, string &y) {
    string a = x;
    string b = y;
    a.append(y);
    b.append(x);
    int n = a.length();
    for (int idx = 0; idx < n; ++idx) {
      if (a[idx] != b[idx]) 
        return a[idx] > b[idx]; 
    }
    return true;
  });
}
The comparison lambda you pass to std::sort must satisfy strict-weak ordering and your lambda does not. If two elements are the same, the lambda should return false;. - Drew Dormann
@πάνταῥεῖ and now, why you should (for programming competitions only!) - user253751