#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>结构就可以将数字映射为字符