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

Jac*_*eng 5 c++ sorting segmentation-fault

有人可以解释为什么下面的排序导致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;
}
Run Code Online (Sandbox Code Playgroud)

在键盘上编译给出:

/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
}
Run Code Online (Sandbox Code Playgroud)

感谢您的所有快速回复.原始的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;
}
Run Code Online (Sandbox Code Playgroud)

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

Unc*_*ens 15

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

它没有定义任何"之前 - 之后"的关系,因此难怪依赖于此属性的算法无法正常运行.


Mih*_*yan 8

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


joh*_*ohn 8

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

bool face_cmp(const A *x, const A *y) {
  return *x < *y;
}
Run Code Online (Sandbox Code Playgroud)

  • 当然,您可以将矢量与<进行比较,请参见http://www.cplusplus.com/reference/stl/vector/operators/.请删除你的选票.我的答案不如其他人好,但并不是不正确的. (2认同)