#include<map>
key/value對
采用紅黑樹實現,鍵值不允許重復
用法與set類似
創建map:
map<string, float> m;
m["haha"] = 11.1;
m["hehe"] = 22.2;
for (map<string, float>::iterator it = m.begin(); it != m.end(); ++it)cout << (*it).first << " : " << (*it).second << endl;
刪除元素:
刪除某個迭代器位置上的元素、等于某個鍵值的元素、一個迭代器區間上的元素
m.erase("haha");
清空map
m.clear();
反向遍歷:
for(map<string, float>::reverse_iterator rit = m.rbegin(); rit != m.rend(); ++rit)cout << (*rit).first << " : " << (*rit).second << endl;
元素的搜索:
map<string, float> =?m.find("hehe"); //按關鍵字搜索,如果找到,返回迭代器位置;未找到,返回end()。
自定義比較函數與set自定義比較函數相同:
1、是結構體,重載"<";
2、不是結構體,構造一個結構體,重載"()",邏輯代碼實現比較
struct desComp
{bool operator()(const string &s1, const string &s2){if (a != b) return a > b;else return a > b;}
};map<string, float, desComp> m;
m["haha"] = 11.1;
m["hehe"] = 22.2;
for (map<string, float, desComp>::it = m.begin(); it != m.end(); ++it)cout << (*it).first << " : " << (*it).second << endl;
用map實現數字分離(字符映射為數字)
map<char,int> m;
for (int i = 0; i < 10; ++i)m['0'+i]=i;
string s="123456";
int a = m[s[3]];//取出第三位上的數字
以上方法采用map<int, char>結構就可以將數字映射為字符