访问地图元素

时间:2014-11-02 13:35:48

标签: c++ map const std

我尝试按如下方式返回std :: map的特定对象:

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)];
}

地图:

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

但是,如果我使用getVertex函数的常量,则会出现编译错误。这是否意味着以这种方式访问​​我的地图元素实际上修改了它的实例?有没有更好的方法来访问我的地图元素?

错误:

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]

1 个答案:

答案 0 :(得分:1)

getVertex是const成员函数

当密钥不存在时,

this->_vertices[std::get<0>(pos)][std::get<1>(pos)]; 可以使用std::map::operator[]修改_vertices地图,因此错误