這是蠻久以前的事情了,那時候為了這個 sort 的問題,發 mail 向侯捷先生請教.雖然隔了很久才回覆我,不過心裡還是很感動~~也才知道自己的程式出了什麼錯.
回覆日期:2003年2月20日 上午 03:38
你的程式寫的邏輯不對。
> bool operator==( const myInt& l, const myInt& r) {
> bool operator>( const myInt& l, const myInt& r) {
> bool operator<( const myInt& l, const myInt& r) {
這三個都沒有完整判斷。sort 的時候,要求 class 需定義 operator<,
而 operator< 在什麼時候應該傳回 0, 什麼時候傳回 正值,什麼時候傳回負值,有一定的規則。
問題不是出在你指的地方,而在這裡。
— jjhou
—– Original Message —–
寄件者: "晏仁"
收件者:
傳送日期: 2002年10月8日 PM 11:07
主旨: 請教 STL sort() 的問題
> Dear 侯sir:
>
> 冒昧請教,以下是程式,而問題在最後面~
>
> #include <iostream>
> #include <algorithm>
> #include <vector>
>
> using namespace std;
>
> class myInt {
> protected:
> int id;
> public:
> myInt():id(0) {};
> explicit myInt( int i ):id(i) {};
> myInt( const myInt& i ):id(i.id) { };
> int getId( void ) const {
> return id;
> }
> myInt& operator=( myInt& i) {
> id=i.id;
> return *this;
> }
> myInt& operator=( int i ) {
> id=i;
> return *this;
> }
> myInt& operator*() { return *this; }
> myInt* operator->() { return this; }
> friend bool operator==( const myInt& l, const myInt& r );
> friend bool operator friend bool operator>( const myInt& l, const myInt& r );
> };
>
> bool operator==( const myInt& l, const myInt& r) {
> if( l.getId() == r.getId() )
> return true;
> }
>
> bool operator>( const myInt& l, const myInt& r) {
> if( l.getId() > r.getId() )
> return true;
> }
> bool operator if( l.getId() return true;
> }
>
> class myIntCompare {
> public:
> int operator()( myInt aa, myInt bb ) {
> if( aa.getId() > bb.getId() )
> return 1;
> if( aa.getId() == bb.getId() )
> return 0;
> if( aa.getId() return -1;
> }
> };
>
> int
> main( int argc, char* argv[] ) {
> const int COUNTS=10000;
> typedef vector intVector_t;
> intVector_t intVector;
> int i;
>
> /**
> * 下面的兩行 code 會導致 segmentation fault,這就是我要問的問題!!
> * for( i=COUNTS;i>=0;–i )
> * intVector.push_back( myInt(i) );
> */
> intVector.reserve( COUNTS );
> for( i=COUNTS; i>=0; –i )
> intVector[i]=i;
>
> // 以下兩種寫法都可以
> sort( intVector.begin(), intVector.end(), myIntCompare() );
> //sort( intVector.begin(), intVector.end() );
>
> for( i=0; i cout << intVector[i].getId() < }
>
> 為什麼把
> intVector.reserve( COUNTS );
> for( i=COUNTS; i>=0; –i )
> intVector[i]=i;
>
> 改成
> for( i=COUNTS;i>=0;–i )
> intVector.push_back( myInt(i) );
>
> 編譯後再執行
> 就會發生 segmentation fault 的問題呢??
> 真的是很奇怪
> 我知道 vector 在配置的時候會先預留一塊記憶體
> 在 push_back() 的時候,如果發現不夠大,會自動重新配置,
> 並把原來的內容搬到新的地方去.
> 我想可能是重新配置的問題~~
> 但卻不知道真正的原因是什麼?
> 希望侯 sir 能給我一些方向,讓我下手去找出答案~
>
> 喔,對了,我的環境是 linux g++ 2.96.
>
> With Best Regards.