繁体   English   中英

为什么std :: sort会对此代码产生分段错误?

[英]Why does std::sort throw a segmentation fault on this code?

有人可以解释为什么下面的排序导致seg错误? 这是g ++(指针的排序向量)的已知错误吗? 我正在使用g ++ 4.5.2进行编译。

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

typedef vector<int> A;
bool face_cmp(const A *x, const A *y) {
  return x != y;
}

int main(int argc, char* argv[]) {

  vector<A *> vec;
  for (int i=0; i<100; i++) {
    vec.push_back( new vector<int>(i%100, i*i) );
  }

  vector<A *>::iterator it;
  sort(vec.begin(), vec.end(), face_cmp);

  return EXIT_SUCCESS;
}

在键盘上编译给出:

/usr/local/lib/gcc/i686-pc-linux-gnu/4.1.2/../../../../include/c++/4.1.2/debug/safe_iterator.h:240:
    error: attempt to decrement a dereferenceable (start-of-sequence)     
    iterator.

Objects involved in the operation:
iterator "this" @ 0x0xbf4b0844 {
type = N11__gnu_debug14_Safe_iteratorIN9__gnu_cxx17__normal_iteratorIPPN15__gnu_debug_def6vectorIiSaIiEEEN10__gnu_norm6vectorIS7_SaIS7_EEEEENS4_IS7_SB_EEEE (mutable iterator);
  state = dereferenceable (start-of-sequence);
  references sequence with type `N15__gnu_debug_def6vectorIPNS0_IiSaIiEEESaIS3_EEE' @ 0x0xbf4b0844
}

感谢您的所有快速回复。 原始的comp函数是:

if (x == y) return false;
if (x->size() < y->size()) return true;
else if (x->size() > y->size()) return false;
else {
  for (register int i=0; i<x->size(); i++) {
    if ((*x)[i] < (*y)[i]) return true;
  }
  return false;
}

我只是更改了第一行并删除了其余部分。 但事实证明它也不是一个严格的弱排序(我忘了如果(* x)[i]>(* y)[i])的情况。 我应该已经发布了整个函数。 不过,再次感谢!!

比较函数必须定义严格的弱排序,这意味着a < bb < a不能同时为真。 您的比较函数没有此属性。

它没有定义任何“之前 - 之后”的关系,因此依赖于此属性的算法无法正常运行也就不足为奇了。

std::sort第三个参数应该是一个函数(或函数对象),如果compare(a, b)true那么compare(b, a)应该为false ,但是你的那个不是这样。 所以你的程序是UB,可以给出任何结果。

没有你的代码是错的。 std :: sort的比较函数必须使用<或等效,使用!=不正确。 可能你想要这个

bool face_cmp(const A *x, const A *y) {
  return *x < *y;
}

将比较函数定义为

bool face_cmp(const A *x, const A *y) {
  return x < y;
}

暂无
暂无

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

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