2012-05-09 3 views
2

私はブーストマルチインデックスコンテナ要素を変更できないことに気づいただけです。これは本当ですか? (以下の単純化されたコードに基づく)は、「更新」機能を見て:どのようにブーストマルチインデックスの読み取り専用の要素を変更するには?

#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:error:読み取り専用オブジェクトのメンバー 'sim_mob :: linkToLink :: currColor'の割り当て

boost tutorialで、イテレータはconstアクセスのみを許可します。この問題を回避するにはどうすればよいですか? ご協力ありがとうございます

答えて

7

マルチインデックスコンテナの要素を変更する3つの方法があります。 links_map_.replace(iterator, new_value)を使用すると、既存の要素を新しい要素で置き換えることができます。 links_map_.modify(iterator, unaryFunctionObject)を使用して、修飾子オブジェクトで要素を変更することができます。最後に、メンバ変数がインデックスの一部でない場合、それをmutableと宣言して直接変更することができます。あなたの例では、後者は正常に動作するはずです。

他の2つの方法については、Boost.MultiIndex Documentationのメンバー関数replacemodifyの仕様を見てください。

編集:あなたの特定のケースでは、mutableとのアプローチは、次のようになります。答えforthe

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

感謝を。コードサンプルを変更して、どこに触れる必要があるかを示すことができれば、もっと有益で助かります(特に私にとって)。変更可能な解決策で十分でしょう。ありがとうございました – rahman

関連する問題