1

Encountered while working on a problem which is hard to describe/explain here as a whole so here is the relevant recreation of the problem.

compiling this code with gnu g++ on windows

int recreate(const map <int , vector<string> > &bitFieldMap){
    cout<<bitFieldMap[1].size();
}
int main(){}

gives the following cryptic error

In function 'int recreate(const std::map > >&)': D:\playground\testit.cpp:12:21: error: passing 'const std::map > >' as 'this' argument of 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](std::map<_Key, _Tp, _Compare, _Alloc>::key_type&&) [with _Key = int; _Tp = std::vector >; _Compare = std::less; _Alloc = std::allocator > > >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = std::vector >; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = int]' discards qualifiers [-fpermissive] cout<

whereas after removing const from recreate function it works well ie

int recreate( map <int , vector< string > > &bitFieldMap){
    cout<< bitFieldMap[1].size() ;
}
int main(){}

In my understanding we use const when the value will remain unaltered signalling the compiler to make some optimizations.Now either the size() function used on the object changes some value each time it is executed or something eerie is going on with some memory allocated to map container upon calling size().

Now my problem can be solved by not using const here or using a multimap. But why does const and size show this behavior ?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Namit Sinha
  • 1,415
  • 3
  • 16
  • 30

2 Answers2

6

You are not calling size() on the map. You are calling operator[] on the map, which is a non-const operation, since it will create an element at that position if one does not already exist.

You then attempt to call size() on the vector<string> at that position, but it is too late by this point. Incidentally, size() is const on Standard Library containers.

BoBTFish
  • 19,167
  • 3
  • 49
  • 76
4

It actually isn't the size that is non-const it is the operator[].

Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218