C++ map

 C++ map

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. #include   <map>   

 

1,map的初始化

 

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. map<char,int> map1;   //空map  
  2. map<char,int> map2(map1.begin(),map2.end()); //   取定范围初始化  
  3. map<char,int> map3(map1);   //复制 map1 的内容初始化  
  4. map<char,int> second;  
  5. second=map1;                // second now contains map1's contents  
  6. map1= map<char,int>();      // and map1 is now empty  

例子:

 

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. #include <map>  
  3. #include <string>  
  4. using namespace std;  
  5. int main ()  
  6. {  
  7.   map<string,int> mymap;//字符串为key,int为value  
  8.   mymap["str1"] = 100;  
  9.   mymap["str2"] = 200;  
  10.   mymap["str3"] = 300;  
  11.   for (map<string,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)  
  12.      cout << it->first << " => " << it->second <<endl;  
  13.   return 0;  
  14. }  

2,迭代器

 

 

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)  
  2.     std::cout << it->first << " => " << it->second << '\n';  

3,容量 Capacity:

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. mymap.empty()  //判断是否为空  
  2. mymap.size()   //The number of elements in the container.  

4, 访问元素 Element access:

 

 

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. mymap['a']="11";  
  2. cout <<mymap['a'] <<endl; //下标法  
  3. mymap.at('a') = 10; //at()方法  

5,修改Modifiers:

 

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. insert()   
  2.   mymap.insert ( std::pair<char,int>('a',100) );  
  3.   std::map<char,int> anothermap;  
  4.   anothermap.insert(mymap.begin(),mymap.find('c'));  //(range insertion)  
  5. erase ()  
  6.   it=mymap.find('b');  
  7.   mymap.erase (it);                   // erasing by iterator  
  8.   mymap.erase ('c');                  // erasing by key  
  9.   it=mymap.find ('e');  
  10.   mymap.erase ( it, mymap.end() );    // erasing by range  
  11. map1.swap(map2); //交换内容,key, value类型相同,个数可以不同  
  12. clear(); //清空元素  

6,操作 Operations:

[cpp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
    1. find() //根据key 找元素  
    2. it = mymap.find('b');  
    3. mymap.find('a')->second    
    4. mymap.count(k); //map中有键值等于k则返回1,否者返回0  
posted @ 2017-05-03 10:53  菜鸡一枚  阅读(346)  评论(0编辑  收藏  举报