2012-05-09 25 views
2

我剛剛注意到,我無法在boost多索引容器元素中進行更改。這是真的? (基於下面的簡化代碼)看看「更新」功能:如何修改boost多索引只讀元素?

#include <boost/multi_index_container.hpp> 
#include <boost/multi_index/ordered_index.hpp> 
#include <boost/multi_index/random_access_index.hpp> 
#include <boost/multi_index/identity.hpp> 
#include <boost/multi_index/member.hpp> 
namespace sim_mob 
{ 
enum TrafficColor 
{ 
    Red =1,    ///< Stop, do not go beyond the stop line. 
    Amber = 2,   ///< Slow-down, prepare to stop before the stop line. 
    Green = 3,   ///< Proceed either in the forward, left, or right direction. 
    FlashingRed = 4, ///future use 
    FlashingAmber = 5, ///future use 
    FlashingGreen = 6 ///future use 
}; 
//Forward declarations 
class Link 
{ 
public: 
    int aa; 
}; 

//////////////some bundling /////////////////// 
using namespace ::boost; 
using namespace ::boost::multi_index; 

typedef struct 
{ 
    sim_mob::Link *LinkTo; 
    sim_mob::Link *LinkFrom; 
// ColorSequence colorSequence; 
    TrafficColor currColor; 
} linkToLink; 


typedef multi_index_container< 
    linkToLink, 
    indexed_by<                 // index 
     random_access<>,//0 
     ordered_non_unique< member<linkToLink,sim_mob::Link *, &linkToLink::LinkTo> >, // 1 
     ordered_non_unique< member<linkToLink,sim_mob::Link *, &linkToLink::LinkFrom> > // 2 
    > 
> links_map; 
class Phase 
{ 
public: 
    typedef links_map::nth_index_iterator<1>::type LinkTo_Iterator; 
    Phase(double CycleLenght,std::size_t start, std::size_t percent): cycleLength(CycleLenght),startPecentage(start),percentage(percent){ 
    }; 

    void update(double lapse) 
    { 
     links_map_[0].currColor = Red; 
    } 

    std::string name; 
private: 
    sim_mob::links_map links_map_; 

}; 
}//namespace 

int main() 
{ 
    sim_mob::Phase F(100,70,30); 
} 

不需要經歷整個程序。請注意,在更新方法中,我得到這個錯誤: multiIndex $ C++ exp2.cpp exp2.cpp:在成員函數'void sim_mob :: Phase :: update(double)'中: exp2.cpp:69: 29:錯誤:在只讀對象中分配成員'sim_mob :: linkToLink :: currColor'

我剛剛在boost tutorial中讀過,迭代器只授予const訪問權限。我該如何解決這個問題? 感謝您的幫助

回答

7

三種不同的方式來改變多索引容器中的元素。您可以使用links_map_.replace(iterator, new_value)替換一個新的元素。您可以使用links_map_.modify(iterator, unaryFunctionObject)來使用修飾符對象更改元素。最後,如果一個成員變量不是任何索引的一部分,您可以聲明它爲mutable並直接更改它。在你的例子中,後者應該可以正常工作。

對於其他兩種方法,請查看Boost.MultiIndex Documentation中的成員函數replacemodify的規範。

編輯:在特定情況下,mutable的做法可能是這樣的:

struct linkToLink 
{ 
    sim_mob::Link* LinkTo; 
    sim_mob::Link* LinkFrom; 
    // simplify write operations to this variable if used in a multi-index 
    // container - bypassing the const-ness. This is possible, because the 
    // variable is not part of any index. 
    mutable TrafficColor currColor; 
}; 
+0

感謝:l,答案。如果您可以修改我的代碼示例以顯示我們需要觸摸的位置以及如何操作,它會更具信息量和更有幫助(尤其對我而言)。可變的解決方案就足夠了。謝謝你和問候 – rahman