访问地图元素
Accessing map elements
我试图返回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
映射,因此出现错误
相关文章:
- 基于多个条件处理地图中的所有元素
- 以C++访问矢量中的地图元素
- 如何知道地图中的最后一个元素是否被删除?
- C++将所有元素从矢量复制到地图/unordered_map的最佳方法
- 如何计算地图中重复元素/值的数量?
- 如何将元素插入到标准::地图的共享指针中?
- 如何从地图访问数组的元素?
- 地图是否将元素存储为 std::p air?
- 从地图上擦除元素,然后将其放回原处
- 如何打印属于地图的一系列元素(std::p air<size_t,std::string>)(不是所有元素)
- 在无序地图中替换元素
- 尝试访问地图中元素时的错误
- 在地图中搜索结构元素
- 如何在地图迭代器中检测最后一个元素
- 在地图中使用擦除的元素
- 为什么在地图中打印第二个元素
- 迭代地图和擦除元素
- 将映射从第二个元素复制到另一个地图
- GDB打印std ::地图元素
- 使用CIN将元素插入C 中的地图