c++中stl的map的[]取下标运算符需要慎用
来源:互联网 发布:文学创作知乎 编辑:程序博客网 时间:2024/06/06 04:20
代码如下:
unordered_map<int,int> un;for(auto it=un.begin();it!=un.end();++it){ int th =it->first+k; auto itf=un.find(th); if(itf != un.end()) //if(un[it->first+k] == 1) //Can use it, it will insert default value, map should use find! { if(k ==0) { if( itf->second >1) count++; } else count++; }}其中un[it->first+k]的用法是错误的,因为取下标运算符会在不存在此元素的前提下,插入<int,default value>的元素,改变了un的大小,导致map遍历的提前结束。
附带一下stl中map的实现:
mapped_type& operator[](const key_type& _Keyval) { // find element matching _Keyval or insert with default mapped iterator _Where = this->lower_bound(_Keyval); if (_Where == this->end() || this->comp(_Keyval, this->_Key(_Where._Mynode()))) _Where = this->insert(_Where, value_type(_Keyval, mapped_type())); return ((*_Where).second); }可见明显的insert语句,所以map的查找,还是老老实实的用find比较合适。
阅读全文
0 0
- c++中stl的map的[]取下标运算符需要慎用
- STL容器map的下标运算符[]
- STL容器map的下标运算符[]
- STL容器map的下标运算符[]
- C++STL中常用的容器下标[]运算
- c++stl map数组下标的使用
- 慎用C++ std::map 的[]运算符
- STL容器vector的下标运算符[]
- STL容器vector的下标运算符[]
- [C++]STL中map的用法
- 【C++】STL中map的详细使用说明
- 下标运算符的重载
- STL map的insert操作与下标操作的区别
- c中取地址运算符&与指针取成员运算符->的优先级
- C++使用STL中map需要注意的地方
- 《关于C++中下标运算符的应用》
- 《关于C++中下标运算符的应用》
- R中向量的下标运算
- 2
- PLSQL学习笔记(二)
- 9.14
- eclispe快捷键
- [leetcode-13] Roman to Integer
- c++中stl的map的[]取下标运算符需要慎用
- 并发基础_14_并发_原子操作类
- 软件框架之EventBus的使用
- BusyBox制作Initramfs嵌入式Linux根文件系统
- void用法
- 两个结构体ifconf和ifreq
- 客户端WebP 图片格式优化
- fedora安装后的配置
- 3.复杂度分析