常量映射元素访问

Const map element access(常量映射元素访问)
本文介绍了常量映射元素访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我尝试使用 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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)