简体   繁体   中英

std::string append segmentation fault

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 third parameter of std::sort needs to satisfy the Compare named requirement , but your lambda clearly violates the requirement of the relationship being antireflexive, ie 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM