C++-试图对2d向量进行排序时,代码崩溃



我正在用C++编写一段代码,它总是给出相同的错误:Segmentation Fault,但我不知道为什么会发生这种情况。我创建了一个小程序,给出了错误。

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int N = 17;
vector<vector<int>> v;
void func(vector<int>& x){
for(int i = 0; i < N; i++){
v.push_back(vector<int>(x));
}
}
int main(){
int n = 5;
vector<int> v2(n, 0);
func(v2);
cout << v.size() << endl; // prints 17
sort(v.begin(), v.end(), [&n](const auto &a, const auto &b){
for(int i = 0; i < n; i++)
if(a[i] != b[i]) return a[i] < b[i]; 
return true;
});
return 0;
}

函数func应该进行递归计算。我通过引用传递v2,因为我从中推送和弹出元素。当我在递归中到达某个点时,我将其添加到全局2d向量v中。

我的代码适用于我尝试过的每一个测试用例,除了这个。

有趣的是,当N<17.

错误发生在lambda排序中。有一个"a"破坏了代码。即使擦除for循环,它仍然会崩溃。

我知道使用全局变量是不好的,但在竞争性编程中,这是一种常见的做法。

我正在编译以下内容:

g++测试.cpp&amp/a.out

我的g++版本:

(Ubuntu 9.3.0-17ubuntu1~20.04(9.3.0

编辑:感谢@DrewDormann,我成功修复了它。

只是将lambda函数的返回值改为false而不是true。

std::sort需要不可伸缩性。来自标准中的[算法排序]

术语strict是指不可伸缩关系(对于所有x!comp(x, x)(的要求

但是,lambda为comp(x, x)返回true


有趣的是,当N<17.

这是未定义的行为。如果它碰巧起作用,那就不吉利了。