#include <map>
1,map的初始化
map<char,int> map1; //空map
map<char,int> map2(map1.begin(),map2.end()); // 取定范围初始化
map<char,int> map3(map1); //复制 map1 的内容初始化
map<char,int> second;
second=map1; // second now contains map1's contents
map1= map<char,int>(); // and map1 is now empty
例子:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main ()
{
map<string,int> mymap;//字符串为key,int为value
mymap["str1"] = 100;
mymap["str2"] = 200;
mymap["str3"] = 300;
for (map<string,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
cout << it->first << " => " << it->second <<endl;
return 0;
}
2,迭代器
for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
3,容量
Capacity
:
mymap.empty() //判断是否为空
mymap.size() //The number of elements in the container.
4, 访问元素
Element access
:
mymap['a']="11";
cout <<mymap['a'] <<endl; //下标法
mymap.at('a') = 10; //at()方法
5,修改Modifiers:
insert()
mymap.insert ( std::pair<char,int>('a',100) );
std::map<char,int> anothermap;
anothermap.insert(mymap.begin(),mymap.find('c')); //(range insertion)
erase ()
it=mymap.find('b');
mymap.erase (it); // erasing by iterator
mymap.erase ('c'); // erasing by key
it=mymap.find ('e');
mymap.erase ( it, mymap.end() ); // erasing by range
map1.swap(map2); //交换内容,key, value类型相同,个数可以不同
clear(); //清空元素
6,操作 Operations:
find() //根据key 找元素
it = mymap.find('b');
mymap.find('a')->second
mymap.count(k); //map中有键值等于k则返回1,否者返回0