const map的初始化及使用
来源:互联网 发布:优盘格式化恢复软件 编辑:程序博客网 时间:2024/05/29 07:07
std::map<int, int>::value_type map_init_data[2] =
{
map<int, int>::value_type(1, 1),
map<int, int>::value_type(2, 2)
};
const map<int, int> a_map(map_init_data, map_init_data + 2);
{
map<int, int>::value_type(1, 1),
map<int, int>::value_type(2, 2)
};
const map<int, int> a_map(map_init_data, map_init_data + 2);
注意构造函数的参数是用[begin, end)定义的,第二个参数应该是首地址加数组长度。
另外:const map不支持中括号操作符,原因是:中括号操作符在无法找到Key时,会插入新的Key,Value的pair,而const不允许此类操作。
具体可以通过查看 std::map 对 operator [] 的实现, 很快就看到问题的所在了:
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);
}
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);
}
上述代码表明:如果 index 不在 map 中, [] 操作符会以 index 为 key 再插入一个 key & value。而const原意并不是这样的, 只是要查找有没有以 index 为 key 的 value 存在。如此则只能通过使用 find 函数进行查询实现,如下:
object *get_object(int index)
{
const map::const_iterator iter = obj_list.find(index);
if (iter != obj_list.end())
{
return iter->second;
}
return NULL;
}
- const map的初始化及使用
- golang语言中map的初始化及使用
- golang语言中map的初始化及使用
- golang语言中map的初始化及使用
- golang语言中map的初始化及使用:代码示例
- golang语言中map的初始化及使用
- c++中静态const型map成员变量的初始化
- Iterator的使用以及map初始化赋值
- const map 成员变量初始化例子
- 初始化private static const map in C++
- C++中 Const 常量的用法,及变量的初始化
- const与指针及初始化
- readonly与const的区别及类成员初始化方法
- C++中static、const和static const的区别及初始化
- const的用法及使用的优点
- C++map的初始化
- static和const的初始化、、
- static/static const 的初始化
- java版 MAC ANSI x 9.9 算法
- sqldeveloper 安装
- php +mysql +apache 整合过程
- apt-get无法找到安装包解决方法--添加源
- Please ensure that adb is correctly located 问题的解决
- const map的初始化及使用
- 一个替换某文件夹下的所有文件中特定字符串的小工具
- 观后感---Jdk的安装和java的核心机制
- 使用logback 替换log4j实例
- 用C语言模拟面向对象
- ETL入门基础与设计讲解
- 一条shell指令统计项目的代码行数
- 华为C8815 默认logcat信息
- LeetCode | 3Sum