有人可以解释为什么以下排序会导致段错误吗?这是g++(指针排序 vector )的已知错误吗?我正在使用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不能都为真。您的比较功能不具有此属性。

它没有定义任何“前后”关系,因此也难怪依赖此属性的算法无法正常运行。

关于c++ - 为什么std::sort会在此代码上引发段错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6978201/

10-17 02:02