[英]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 < b
和b < 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.