STL的list和map使用的几个小问题

1.list的front函数和back函数,在list空时,直接调用,在不同平台上返回结果不同,会返回未知错误,因此调用前务必要判断是否空。Calling this function on an empty container causes undefined behavior.

2.map的[]操作符,可以用来进行键值赋值,但不可以直接用来判断或赋值给其它变量,如:

std::map<int, int> mymap;

mymap[1] = 100;//ok,mymap.size() =1

int n = mymap[2];//此时,将会增加了一个key为2,value为NULL。mymap.size=2。

因此最后的方法,是使用find函数。

----

If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).

但对于at,如果key不存在,会抛出异常。
A similar member function, map::at, has the same behavior when an element with the key exists, but throws an exception when it does not.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值