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 ?