c++ - 如何在 C++ 中实现多维映射的常量正确性

标签 c++ dictionary multidimensional-array constants

我有一个复杂的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/

相关文章:

c++ - 静态库,但我仍然需要标题?

c# - 从外部应用程序读取屏幕上的文本。 API Hook ?

c++ - 当没有更多引用时如何从缓存中删除智能指针?

python - 返回嵌套字典中的所有键以及值

python - 字典:恢复/删除设置默认值

javascript - JavaScript 对象中键查找的性能

PHP:使用数组在另一个多维数组中获取值

c++ - 已编译库的 header 无法相互访问

c - 为什么 248x248 是我可以声明的最大二维数组大小?

javascript - 返回多维数组 0 的函数