2017-06-01 47 views
2

我有一個複雜的map,最後,它存儲指向Drawable對象的指針。 Drawable對象具有draw()成員函數,聲明爲const。我需要撥打全部draw函數爲存儲在我的地圖中的某個類型的所有對象,並且我必須在constconst函數中執行此操作。不過,我似乎無法保留我的函數的常量正確性(drawSolid)。如何在C++中實現多維地圖中的const正確性

我的外部地圖(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

與您的問題無關,但不要使用兩個前導下劃線來創建自己的符號,這些符號在「實現」(編譯器和標準庫)的所有作用域中保留。請參閱[這個老問題和它的答案](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier)瞭解更多信息。 –

+0

你用const聲明得到了什麼錯誤? –

+0

我現在要更新這個問題,但這是我得到的:'/home/carles/Development/dss-sim/src/graphics/DrawableItems.cpp:51:35:error:passing'const std :: map < DrawableItems ::的ItemType,性病::矢量<性病:: shared_ptr的>>」爲 '這個' 參數丟棄限定符[-fpermissive] 其=儷>第二[SOLID];' –

回答

2

還有就是operator[]std::map沒有const版本。然而,有一個at()一個const版本,你可以改用:

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

的原因是operator[]插入一個元素,如果沒有元素還,所以不能有一個constoperator[]。如果沒有元素存在,則
at()會拋出異常,並且這與const std::map兼容。

+0

那是它,非常感謝! –