ice*_*ere 88 c++ stl const map
我试图使用operator []访问const C++映射中的元素,但此方法失败.我也尝试用"at()"来做同样的事情.这次工作.但是,我找不到任何关于使用"at()"来访问const C++映射中的元素的引用."at()"是C++地图中新添加的函数吗?我在哪里可以找到更多关于此的信息?非常感谢你!
一个例子如下:
#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
}
Run Code Online (Sandbox Code Playgroud)
对于使用"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
Kon*_*lph 32
如果a中不存在元素map,operator []则会添加它 - 这显然不能在const映射中工作,因此C++不定义const运算符的版本.这是编译器类型检查器防止潜在运行时错误的一个很好的例子.
在你的情况,你需要使用find,而不是将仅如果存在返回(迭代器)元素,它永远不会改变map.如果某个项不存在,则会向地图返回一个迭代器end().
at不存在,甚至不应该编译.也许这是一个"编译器扩展"(=一个bug 新的C++ 0x).
| 归档时间: |
|
| 查看次数: |
45466 次 |
| 最近记录: |