Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
Will this compile?
#include <map> |
Answer: No, it will give the following compile error:
When using Borland BCC32.EXE version 6.0.10.157:
[C++ Error] Unit1.cpp(6): E2094 'operator+' not implemented in type '_STL::map<int,double,_STL::less<int>,_STL::allocator<_STL::pair<const int,double> > >' for arguments of type 'int' |
When using G++ 4.5.2:
/MyFolder/CppGetValueInMap/main.cpp:5: error: passing 'const std::map<int, double>' as 'this' argument of 'mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = int, _Tp = double, _Compare = std::less<int>, _Alloc = std::allocator<std::pair<const int, double> >, mapped_type = double, key_type = int]' discards qualifiers |
The reason for this is that the index operator/operator[] is not a const member function. This is because this member function possibly inserts an element to the std::map! It is created to make insertion easy and to never throw. Therefore, the code above will not compile: if myMap does not have the key i, an exception has to be thrown. So, due to this it does not compile. The way to solve the above example is shown below.
#include <cassert> |
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.