[英]std::string append segmentation fault
I encounter the error below when solving the leetcode problem https://leetcode.com/problems/largest-number/ .在解决 leetcode 问题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). (顺便说一句,当矢量大小较小时,它可以毫无问题地运行,例如 10)。 I already read the solutions, so I know there is a better way to do solve this leetcode problem.我已经阅读了解决方案,所以我知道有更好的方法来解决这个 leetcode 问题。 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
. std::sort
的第三个参数需要满足Compare named 要求,但您的 lambda 显然违反了反反关系的要求,即对于任何a
, comp(a, a)
必须产生false
,传递字符串"0"
因为这两个参数导致a
和b
在循环之前都是"00"
并且循环完成而不返回导致true
而不是所需的false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.