Accessing Elements in a Const Map: Operator[] vs. at()
When working with constant maps, accessing elements using operator[] may fail. However, using at() is a viable alternative. Why is this the case?
In a non-const map, operator[] performs two functions:
However, in a const map, operator[] is not allowed to modify the underlying data structure. Hence, it can only perform the first function and throws an error when trying to insert a new element using the second function.
In contrast, at() is a method introduced in C 11 specifically for accessing elements in a const map. It provides several benefits:
For these reasons, at() is the recommended method for accessing elements in a const std::map. The example code:
#include <iostream> #include <map> int main() { std::map<int, char> A; A[1] = 'b'; A[3] = 'c'; const std::map<int, char>& B = A; std::cout << B.at(3) << std::endl; // it works std::cout << B[3] << std::endl; // it does not work }
Will output:
c error: can't access elements with operator[] in a const std::map
The above is the detailed content of Const Map Access: Why Use `at()` Instead of `operator[]`?. For more information, please follow other related articles on the PHP Chinese website!