0

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;
  });
}
  • 2
    [`#include +`](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – πάντα ῥεῖ Jul 28 '22 at 18:31
  • 2
    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 Jul 28 '22 at 18:37
  • @πάνταῥεῖ and now, [why you should](https://stackoverflow.com/a/33764128/106104) (for programming competitions only!) – user253751 Jul 28 '22 at 18:37
  • 3
    The only "competition" that matters is making a successful living as a professional engineer. "Competitive" programming sites are at-best novelty, on-average pointless, and at-worst damaging to the development of professional skills. They are flat-out cancer on the software engineering community, particularly to the fresher engineering prospects that naively believe they're actually learning something career enhancing. Ultimately all they do is hone people's skills at writing really crappy code quickly. We have enough of that already; we won't need sites enhancing that 'skill' further. – WhozCraig Jul 28 '22 at 18:45

1 Answers1

5

The third parameter of std::sort needs to satisfy the Compare named requirement, but your lambda clearly violates the requirement of the relationship being antireflexive, i.e. for any a, comp(a, a) must yield false, passing the string "0" as both parameters results in both a and b being "00" before the loop and the loop completes without returning resulting in true instead of the required false.

fabian
  • 80,457
  • 12
  • 86
  • 114