C++:STL map 的 find 方法与 operator[] 运算符区别
map::find 是 Get 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[] 做了一次插入动作,导致不期望的错误结果。
参考: