"Forced constness" in std::map<std::vector<int>,double> > ?

Posted by Peter Jansson on Stack Overflow See other posts from Stack Overflow or by Peter Jansson
Published on 2010-04-23T06:51:45Z Indexed on 2010/04/23 7:03 UTC
Read the original article Hit count: 214

Filed under:

Consider this program:

#include <map>
#include <vector>
typedef std::vector<int> IntVector;
typedef std::map<IntVector,double> Map;
void foo(Map& m,const IntVector& v)
{
   Map::iterator i = m.find(v);
   i->first.push_back(10);
};
int main()
{
   Map m;
   IntVector v(10,10);
   foo(m,v);
   return 0;
}

Using g++ 4.4.0, I get his compilation error:

test.cpp: In function 'void foo(Map&, const IntVector&)':
test.cpp:8: error: passing 'const std::vector<int, std::allocator<int> >' as 'this' argument of 'void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = int, _Alloc = std::allocator<int>]' discards qualifiers

I would expect this error if I was using Map::const_iterator inside foo but not using a non-const iterator.

What am I missing, why do I get this error?

© Stack Overflow or respective owner

Related posts about c++