首页 文章

C const map元素访问

提问于
浏览
71

我试图使用operator []访问const C map中的元素,但是这个方法失败了 . 我也尝试用“at()”来做同样的事情 . 这次工作 . 但是,我找不到任何关于使用“at()”来访问const C map中的元素的引用 . “at()”是C Map 中新添加的功能吗?我在哪里可以找到更多关于此的信息?非常感谢你!

一个例子可能如下:

#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]”,它在编译期间返回以下错误:

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

使用的编译器是g 4.2.1

4 回答

  • 2

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

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

    由于这种行为, at()const 重载是有道理的,与 operator[] 不同, operator[] 总是有可能改变 Map .

  • 94

    如果 map 中不存在元素,operator []将添加它 - 这显然不能在 const 映射中工作,因此C不定义运算符的 const 版本 . 这是编译器类型检查器防止潜在运行时错误的一个很好的例子 .

    在您的情况下,您需要使用find而不是只返回(迭代器)元素(如果存在),它永远不会修改 map . 如果某个项不存在,则会将迭代器返回到 Map 的 end() .

    at 不存在,甚至不应该编译 . 也许这是一个“编译器扩展”(= C 0x中的一个新bug) .

  • 29

    如果给定的键不存在,[] -operator将在 Map 中创建一个新条目 . 因此它可能会改变 Map .

    link .

  • 3

    这对我来说非常意外,但STL Map 没有 const 索引运算符 . 也就是说, B[3] 不能是只读的 . 从手册:

    Since operator[] might insert a new element into the map, it can't possibly be a const member function.

    我不知道 at() .

相关问题