如何在C ++中实现多维映射中的const-correctness

时间:2017-06-01 08:56:49

标签: c++ dictionary multidimensional-array const

我有一个复杂的map,最后会存储指向Drawable个对象的指针。 Drawable个对象具有draw()成员函数,该函数声明为 const 。我需要为地图中存储的特定类型的所有对象调用所有 draw函数,我必须在 const 功能。但是我似乎无法保持函数的常量(drawSolid)。

我的外部地图(map<int, ##>)实质上是索引一些子地图。子图依次是索引向量(map<ItemType, vector<##> >)。最后,此向量保留一组shared_ptr<Drawable>个对象。

如果我从函数标题中删除 const 限定符,则所有内容都会编译,但我需要 const 。我如何迭代我的多维地图,保持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)

1 个答案:

答案 0 :(得分:2)

std::map中没有operator[]的常量版本。但是,您可以使用at()的const版本:

its = li->second.at(SOLID);

原因是如果没有元素,operator[]会插入一个元素,因此const版本不会operator[]。{
如果没有元素存在,at()会引发异常,这与const std::map兼容。