我試圖使用operator []訪問const C++映射中的元素,但此方法失敗。我也試圖用「at()」來做同樣的事情。它這次工作。但是,我找不到有關使用「at()」訪問const C++映射中的元素的任何參考。 「at()」是C++ map中新增的函數嗎?我在哪裏可以找到關於此的更多信息?非常感謝你!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
}
對於使用 「B [3]」,它在編譯期間返回如下錯誤:
t01.cpp:14: error: passing ‘const std::map, std::allocator > >’ 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 >]’ discards qualifiers
使用的編譯器爲g ++ 4.2.1
可以讓「at」返回一個默認值而不是拋出異常嗎? – user1202136
'at()'應該只用C++ 11 – Deqing
我在VS2013中使用'at()'來設置使用VS2010工具包的項目。我認爲這意味着我沒有使用C++ 11 ...但它編譯...? – thomthom