访问地图元素

Accessing map elements

本文关键字:元素 地图 访问      更新时间:2023-10-16

我试图返回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]

getVertex是常量成员函数

当密钥不存在时,this->_vertices[std::get<0>(pos)][std::get<1>(pos)];可以使用std::map::operator[]修改_vertices映射,因此出现错误