0

I try to return a specific object of my std::map as follows :

const Vertex& Graph::getVertex(const std::pair<size_t, size_t>& pos) const // -> compile error
{
   return this->_vertices[std::get<0>(pos)][std::get<1>(pos)];
}

Map :

std::map<size_t, std::vector<Vertex>> _vertices;

However, I get a compilation error if I let the constness of my getVertex function. Does it mean that accessing my map elements this way actually modify its instance ? Is there a better way to access my map elements ?

The error :

error: passing ‘const std::map<unsigned int, std::vector<Vertex> >’ as ‘this’ argument of ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::o\
   perator[](const key_type&) [with _Key = unsigned int; _Tp = std::vector<Vertex>; _Compare = std::less<unsigned int>; _Alloc = std::allocator<std::pair<const unsigned int, std::vector<Vertex> > >; std::map\
   <_Key, _Tp, _Compare, _Alloc>::mapped_type = std::vector<Vertex>; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = unsigned int]’ discards qualifiers [-fpermissive]
Kernael
  • 3,270
  • 4
  • 22
  • 42

1 Answers1

1

getVertex is const member function

this->_vertices[std::get<0>(pos)][std::get<1>(pos)]; can modify the _vertices map using std::map::operator[] when key doesn't exists , hence the error

P0W
  • 46,614
  • 9
  • 72
  • 119