Reputation: 11
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;
});
}
Upvotes: 0
Views: 402
Reputation: 82461
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
.
Upvotes: 5