使用STL模板必須重載的運算符

STL各種容器和算法的sort和find函數對重載運算符的調用情況:

1) 二叉樹類型的容器的sort和find都會調用operator < 。

2)線性類型容器sort會調用operator <;線性容器使用std::find會調用operator ==。

需要非常注意重載<運算符,分類討論要周全。不然重則會導致dump機問題,輕則會導致排序不對。

對於< 號的重載要滿足嚴格弱序的要求。

嚴格弱序定義如下:

 x R x 爲false

x R y => !(y R x)   另一種表示爲    !(x R y) && !(y R x) 則 x=y

 x R y 且 y R z 則 x R z


下面調用find 函數測試在set中find調用了< 關係,(去掉註釋,調用stl 標準的find函數會調用 == 關係)

#include <iostream>
#include <set>
using namespace std;
 struct s{
    int x,y;
    s(int xx,int yy):x(xx),y(yy){}
    bool operator <(const s& tmp) const {
        if(x < tmp.x){
            return true;
        }
        else if(y < tmp.y){
            return true;
        }
        return false;
    }
 };
set<s> ms;
int main(){
        ms.insert(s(31,41));
        s test(31,41);
        s test2(32,41);
        if(test < test2){
            cout<<" test<test2"<<endl;
        }
        //auto itt = find(ms.begin(),ms.end(),test);
        auto itt = ms.find(test);
        if(itt!= ms.end()){
            cout<< "find the value: "<<itt->x<<endl;
        }
        else{
             cout<<"not found"<<endl;
        }
}

發佈了35 篇原創文章 · 獲贊 36 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章