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


注意构造函数的参数是用[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);
  }
 
上述代码表明:如果 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;
}


原创粉丝点击