如何修改boost多索引的只读元素?

时间:2012-05-09 06:13:23

标签: c++ boost boost-multi-index

我刚刚注意到我无法在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访问权限。我该如何解决这个问题? 谢谢你的帮助

1 个答案:

答案 0 :(得分: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;
};