VC++/map

Map是c++的一个标准容器,它提供了很好一对一的关系,在一些程序中建立一个map可以起到事半功倍的效果,总结了一些map基本简单实用的操作!

计算时间差可以用  :

long t2,t1,t3;

 当前时间 t1=time(0); 距离1990年的秒数

  时间差(秒数)              t3=t1-t2;

<span style="color:#009900">#include <map>
#include<iostream>
using namepsace std
map<CString,long> mapTest;

map<CString,long>::iterator itmap;

CString str="111";</span>

一、添加

    1.使用[]进行单个插入

<span style="color:#009900">mapTest[str]=time(0);    //以str为key键,从小到大排序   如果已经存在str,赋值将会修改对应的long 值</span>

    2.使用insert进行单个或多个插入

<span style="color:#009900">  <span style="color:#3333ff">// 1.插入单个键值对,并返回插入位置和成功标志,插入位置已经存在值时,插入失败</span>
  pair<std::map<CString,long>::iterator,bool> ret;   
  str="222";

  ret=mapTest.insert(str::pair<CString,long>(str,time(0));  //单个插入
  if(ret.second == false)
     count<<ret.first->first<<":已经存在,值为:"<<ret.first->second<<endl;

  <span style="color:#3333ff"> //2.指定位置插入    不同位置插入效率不同,因为涉及到重排
</span>    itmap=mapTest.begin();
    mapTest.insert(itmap,pair<CString,long>(str,time(0)));
 
  <span style="color:#3366ff">//3.插入多个</span>
    map<CString,long> mapanother;
    mapanother.insert(mapTest.begin(),mapTest.find("222"));
  
  <span style="color:#3333ff">//4.列表形式插入多个</span>
    mapanother.insert({{"444",time(0)},{"555",time(0)}});     
</span>

二、删除

//删除迭代器指向位置的键值对,并返回一个指向下一个元素的迭代器
iterator  erase(iterator pos);  
     
//删除一定范围内的元素,并返回指向下一个元素的迭代器
iterator erase(const_iterator first,const_iterator last);

//根据key值来删除,返回删除的元素数量   在map里非0即1
size_t erase(const key_type&key)

//清空map,清空后size为0
void clear();

);  
     
//删除一定范围内的元素,并返回指向下一个元素的迭代器
iterator erase(const_iterator first,const_iterator last);

//根据key值来删除,返回删除的元素数量   在map里非0即1
size_t erase(const key_type&key)

//清空map,清空后size为0
void clear();

三、查找

 
//关键字查询,找到则返回指向该关键字的迭代器,否则返回指向end的迭代器
itmap=mapTest.find(str); 
if(itmap==mapTest.end())
    count<<"未找到"<<endl;

4.map最后一个元素

mapTest.rbegin() //最大值的迭代器
itmap=mapTest.find(str); 
if(itmap==mapTest.end())
    count<<"未找到"<<endl;

4.map最后一个元素

mapTest.rbegin() //最大值的迭代器

四、取值

Map中元素取值主要有at和[ ]两种操作,at会作下标检查,而[]不会

//ID_Name中没有关键字2016,使用[]取值会导致插入
//因此,下面语句不会报错,但打印结果为空
cout<<mapTest["999"]<<endl;

//使用at会进行关键字检查,因此下面语句会报错
ID_Name.at("999") = "777";
cout<<mapTest["999"]<<endl;

//使用at会进行关键字检查,因此下面语句会报错
ID_Name.at("999") = "777";

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值