常量映射元素访问 [英] Const map element access

查看:28
本文介绍了常量映射元素访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 operator[] 访问 const map 中的元素,但此方法失败.我也尝试使用 at() 来做同样的事情.这次成功了.但是,我找不到任何关于使用 at() 访问 const map 中的元素的参考.at()map新增的函数吗?我在哪里可以找到有关此的更多信息?非常感谢!

I tried to use the operator[] access the element in a const map, but this method failed. I also tried to use at() to do the same thing. It worked this time. However, I could not find any reference about using at() to access element in a const map. Is at() a newly added function in map? Where can I find more info about this? Thank you very much!

示例如下:

#include <iostream>
#include <map>

using namespace std;

int main()
{
        map<int, char> A;
        A[1] = 'b';
        A[3] = 'c';

        const map<int, char> B = A;

        cout << B.at(3) << endl; // it works
        cout << B[3] << endl;  // it does not work

}

使用B[3]",编译时返回如下错误:

For using "B[3]", it returned the following errors during compiling:

t01.cpp:14: 错误:传递‘conststd::map>>’ 作为‘_Tp&’的‘this’参数std::map<_Key, _Tp, _Compare,_Alloc>::operator[](const _Key&) [with _Key = int, _Tp = char, _Compare = std::less, _Alloc =std::allocator>]' 丢弃限定符

t01.cpp:14: error: passing ‘const std::map<int, char, std::less, std::allocator<std::pair<const int, char> > >’ as ‘this’ argument of ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = int, _Tp = char, _Compare = std::less, _Alloc = std::allocator<std::pair<const int, char> >]’ discards qualifiers

使用的编译器是g++ 4.2.1

The compiler used is g++ 4.2.1

推荐答案

at() 是 C++11 中 std::map 的新方法.

如果具有给定键的元素不存在,则不会像 operator[] 那样插入新的默认构造元素,而是抛出 std::out_of_range 异常.(这类似于 at() 对于 dequevector 的行为.)

Rather than insert a new default constructed element as operator[] does if an element with the given key does not exist, it throws a std::out_of_range exception. (This is similar to the behaviour of at() for deque and vector.)

由于这种行为,at()const 重载是有意义的,不像 operator[] 总是有改变地图的潜力.

Because of this behaviour it makes sense for there to be a const overload of at(), unlike operator[] which always has the potential to change the map.

这篇关于常量映射元素访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆