Access to C ++ element const

I tried using the [] operator to access an element on a C ++ const map, but this method failed. I also tried using "at ()" to do the same. He worked this time. However, I could not find references to using "at ()" to access an element in a C ++ const map. Is the "at ()" function a newly added function on a C ++ map? Where can I find more information about this? Thank you very much!

An example would be the following:

#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 } 

To use "B [3]", the following errors were returned at compile time:

t01.cpp: 14: error: passing 'const std :: map, std :: allocator → as' this argument' _Tp & std :: map <_Key, _Tp, _Compare, _Alloc> :: operator [] (const _Key & ) [with _Key = int, _Tp = char, _Compare = std :: less, _Alloc = std :: allocator>] discards qualifiers

The g ++ 4.2.1 compiler is used

+58
c ++ stl const map
Feb 27 '11 at 17:17
source share
4 answers

at() is a new method for std::map in C ++ 11.

Instead of inserting a new default element constructed as operator[] , if the element with the given key does not exist, it throws an exception std::out_of_range . (This is similar to the at() behavior for deque and vector .)

Because of this behavior, const at() overloading makes sense, unlike operator[] , which always has the potential to change the map.

+73
Feb 27 2018-11-11T00:
source share
— -

If the element does not exist in the map , operator [] adds it - which obviously cannot work in the const map, therefore C ++ does not determine the version of the const operator. This is a good example of compiler type checking, preventing a potential runtime error.

In your case, you need to use find , which will only return the element (iterator to the), if it exists, it will never change the value of map . If the element does not exist, it returns an iterator to the end() maps.

at does not exist and should not compile. Perhaps this is a "compiler extension" (= mistake new in C ++ 0x).

+25
Feb 27 2018-11-21T00:
source share

The [] operator will create a new entry on the map if the given key does not exist. This may change the map.

See the link.

+3
Feb 27 2018-11-11T00:
source share

It comes as a surprise to me, but there is no const index operator on the STL map. That is, B[3] cannot be read-only. From the manual:

Since the operator [] can insert a new element into the map, it cannot be a constant function.

I have no idea about at() .

+2
Feb 27 2018-11-11T00:
source share



All Articles