我有一个复杂的map
最后,存储指向 Drawable
的指针对象。 Drawable
对象有 draw()
声明为 const
的成员函数。我需要调用所有 draw
函数用于存储在我的 map 中的特定类型的所有对象,并且我必须在 const
内执行此操作 功能。但是,我似乎无法保留函数的 const 正确性( drawSolid
)。
我的外部 map ( map<int, ##>
)本质上是对一些子 map 进行索引。子映射又是索引 vector ( map<ItemType, vector<##> >
)。最后,这个 vector 保留了一组 shared_ptr<Drawable>
对象。
如果我删除 const
来 self 的函数头的限定符,一切都可以编译,但我需要它是 const
。我如何迭代我的多维映射,保持常量正确性?
void DrawableItems::drawSolid(int item_list = -1) const
{
typedef std::map<int, std::map<ItemType, std::vector<std::shared_ptr<Drawable> > > > drawablemap;
std::vector<std::shared_ptr<Drawable> > its;
for(drawablemap::const_iterator li = __items.begin(); li != __items.end(); li++) {
its = li->second[SOLID];
for(auto di = its.begin(); di != its.end(); di++) {
di->get()->draw();
}
}
}
这是我从编译器(G++)得到的错误:
/.../dss-sim/src/graphics/DrawableItems.cpp: In member function ‘void DrawableItems::drawSolid(int) const’:
/.../dss-sim/src/graphics/DrawableItems.cpp:51:35: error: passing ‘const std::map<DrawableItems::ItemType, std::vector<std::shared_ptr<Drawable> > >’ as ‘this’ argument discards qualifiers [-fpermissive]
its = li->second[SOLID];
^
In file included from /usr/include/c++/5/map:61:0,
from /.../dss-sim/src/common/dss.hpp:11,
from /.../dss-sim/src/graphics/DrawableItems.hpp:19,
from /.../dss-sim/src/graphics/DrawableItems.cpp:15:
/usr/include/c++/5/bits/stl_map.h:494:7: note: in call to ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](std::map<_Key, _Tp, _Compare, _Alloc>::key_type&&) [with _Key = DrawableItems::ItemType; _Tp = std::vector<std::shared_ptr<Drawable> >; _Compare = std::less<DrawableItems::ItemType>; _Alloc = std::allocator<std::pair<const DrawableItems::ItemType, std::vector<std::shared_ptr<Drawable> > > >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = std::vector<std::shared_ptr<Drawable> >; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = DrawableItems::ItemType]’
operator[](key_type&& __k)
最佳答案
operator[]
没有 const 版本在std::map
中。但是,有 at()
的 const 版本。您可以使用它来代替:
its = li->second.at(SOLID);
原因是 operator[]
在还没有元素的情况下插入一个元素,因此不可能有 operator[]< 的
。const
版本
另一方面,如果不存在元素,at()
会引发异常,这与 const std::map
兼容。
关于c++ - 如何在 C++ 中实现多维映射的常量正确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44302895/