C++:STL map 的 find 方法与 operator[] 运算符区别

C++:STL map 的 find 方法与 operator[] 运算符区别

map::findGet iterator to element

map::operator[]Access element

最大的区别是当待查找的 KEY 不存在时:

1.map::find 返回一个空迭代器(map::end)。

2.map::operator[] 将用 VALUE 默认的构造函数创建一个对象并插入到 map 中,将其返回。


std::map::operator[]

If k matches the key of an element in the container, the function returns a reference to its mapped value.

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).


这就需要我们要很小心:如果你只是想看看 map 中有没有你想要的 KEY-VALUE,要用 find 方法,不要用 []!

#include <iostream>
#include <string>
#include <vector>
#include <map>

using namespace std;

int main()
{
    map<string, vector<int> > mapObj;
    map<string, vector<int> >::iterator mapIt;
    mapIt = mapObj.find("test1280");
    if (mapIt != mapObj.end())
        cout<<"found"<<endl;
    else
        cout<<"not found"<<endl;
    return 0;
}

如果你希望当某 KEY-VALUE 不存在时,创建一个键值对并将对应的值返回,可以使用 operator[] 。


这是个大坑。

coding 时查了很长时间,明明没有执行插入动作,为什么还有对应的 KEY-VALUE 键值对呢?

最后定位到,原来是 operator[] 做了一次插入动作,导致不期望的错误结果。


参考:

1.http://www.cplusplus.com/reference/map/map/find/

2.http://www.cplusplus.com/reference/map/map/operator[]/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值