简体   繁体   English

分类功能中的细分错误

[英]Segmentation fault in sort function

I am working on a code that sorts a 2d vector based on it's first column, The code gives out a segmentation fault on the input 我正在研究根据其第一列对2d向量进行排序的代码,该代码在输入中给出了分段错误

6
7 1 3 4 1 7 

Code: 码:

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
bool sortcol(const vector <int> v1,const vector <int> v2){
 return v1[0]<v2[0];
}
int main() {
int n;
cin>>n;
vector < vector<int> > v(n);
for(int i=0;i<n;i=i+1){
    vector <int> temp2;
    int temp;
    cin>>temp;
    temp2.push_back(temp);
    temp2.push_back(i);
    v.push_back(temp2);
}
sort(v.begin(),v.end(),sortcol);
return 0;
}

The problem is in this declaration of your vector: 问题在于您的向量的以下声明:

vector<vector<int>> v(n);

It does not simply reserve n spots, it creates a vector with n empty vectors inside. 它不只是保留n斑点,它还创建了一个内部有n空向量的向量。 Hence the first call to sortcol for any of these empty entries produces undefined behavior, because 因此,对于这些空条目中的任何一个,对sortcol的第一次调用sortcol产生未定义的行为,因为

return v1[0] < v2[0];

references non-existent element at position zero. 引用位置零处不存在的元素。

Replace the declaration with 将声明替换为

vector<vector<int>> v;

to fix this problem. 解决此问题。 If you would like to reserve space for n entries, add a call to vector::reserve after the declaration: 如果要为n个条目保留空间,请在声明后添加对vector::reserve的调用:

vector<vector<int>> v;
v.reserve(n);

You should also pass vectors to your comparator by const reference, rather than by const value. 您还应该通过const引用而不是const值将向量传递给比较器。

The problem is that you are trying to reserve the wrong way in this particular case. 问题是您在这种情况下试图保留错误的方式。 Use 采用

    v.reserve(n);

instead. 代替。

Your comparator has 2 issues: 您的比较器有2个问题:

bool sortcol(const vector <int> v1,const vector <int> v2){
   return v1[0]<v2[0];
}
  • it does not check if vectors passed to it do have at least one element 它不会检查传递给它的向量是否确实具有至少一个元素

  • you should pass vectors by const reference (this is not error, but can lead to bad performance issue) 您应该通过const引用传递向量(这不是错误,但是会导致性能问题)

So in your code: 因此,在您的代码中:

vector < vector<int> > v(n);

you create v with n empty vectors and then you push back additional data after it. 您用n空向量创建v ,然后在其后推回其他数据。 Then you try to sort it and you get UB with your comparator when it hits empty vectors you created. 然后,您尝试对其进行排序,当比较器遇到您创建的空向量时,您将使用比较器得到UB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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