c map 使用自定義結構做關鍵字

2021-07-28 11:54:08 字數 1453 閱讀 7180

map在stl中的定義

template , class alloc = alloc>

第乙個引數key是關鍵字型別

第二個引數t是值型別

第三個引數compare是比較函式(仿函式)

第四個引數是記憶體配置物件

map內部儲存機制實際是以紅黑樹為基礎,紅黑樹在插入節點時,必須依照大小比對之後在乙個合適的位置上執行插入動作。所以作為關鍵字,起碼必須有「<」這個比較操作符。我們知道,int,float,enum,size_t等等簡單關鍵字,都有內建的比較函式,與map搭配無論是插入還是查詢,都沒什麼問題。但是作為複雜資料型別,如果沒有明確定義「<」比較操作符,就不能與map直接搭配使用,除非我們自己定義第三個引數。

在選擇map的關鍵字時,注意以下兩點,同時這兩點也是改錯的方法:

a) 關鍵字明確定義「<」比較操作符

b) 沒有「<」比較操作符,自定義仿函式替代第三個引數compare,該仿函式實現「()」操作符,提供比較功能。插入時各節點順序以該仿函式為綱。

以std::pair為關鍵字摻入map

下面我們先寫乙個有錯誤的函式,在分析錯誤原因之後,逐步進行修正。

#include

int main()

這個程式一定失敗,如果非要如此使用,上述a方法顯然不適合,std::pair是已定義好的結構體不可修改。只能使用b方法了,定義乙個比較類改造如下:

#include struct comp  

};

int main()

#include struct st  

st(int x, int y):a(x), b(y){}

};

int main()

#include #include using namespace std;

class key

; bool operator <(const key &key1,const key &key2)

; bool key::operator <(const key &key) const

{ if(this->_keyclassmap;

key one(1);

classmap.insert(make_pair(one,1));

key two(2);

classmap.insert(make_pair(two,2));

key three(3);

classmap.insert(make_pair(three,3));

map::iterator itor=classmap.begin();

while(itor!=classmap.end())

{ cout

RF(自定義關鍵字)

1 在 d work software python lib site packages 資料夾下,新建 python package 包 例如我的是 testlibrary 2 在 d work software python lib site packages testlibrary 資料夾下檢...

RF 自定義關鍵字和關鍵字引數

使用者自定義關鍵字 使用者關鍵字語法 settings library seleniumlibrary keywords open browser chrome input text id kw 京東 click button id su close browser test cases case0...

自定義關鍵字的步驟

假設python的安裝路徑在d 下面 第一步 在d python lib site packages 建立庫檔案資料夾 mylibrary 第二步 在mylibrary內建立 mytool.py 檔案 這個檔案裡面寫自己需要穿件的關鍵字既方法,如下 裡面有乙個比較兩引數大小的方法,在robot fr...