C++ 映射容器map

#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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值