boost multi_index_container broken indexes

127 views Asked by At

I have a multi_index container. Chan::Ptr is a shared_pointer to the object. The container has two indexes with object functions.

typedef multi_index_container<
    Chan::Ptr,
        indexed_by<
        ordered_unique<const_mem_fun<Chan,string,&Chan::Channel> >,         
        ordered_non_unique<const_mem_fun<Chan,string,&Chan::KulsoSzam> > >
    > ChanPtrLista;

Until I push_back objects only into the container, all searching in container is successful.

When I modify the values in the objects (example: Chan::Channel changes) index will be broken. Listing the container with an index, give back a wrong order. However the find functions isn't work anymore.

How can I re-index the container? ("rearragne" method do nothing with indexes).

1

There are 1 answers

2
Karl Nicoll On BEST ANSWER

When making changes to an item inside a Boost multi index, you should use the modify method exposed by the index object. The modify method has the following signature:

bool modify(iterator position, Modifier mod);

Where:

  • position is an iterator pointing to the item to update
  • mod is a functor that accepts a single parameter (the object you want to change).

It returns true if the modification occurred successfully, or false if it failed.

When the modify function is run, the functor updates the item you want to change, and then the indexes are all updated.

Example:

class ChangeChannel
{
public:
  ChangeSomething(const std::string& newValue):m_newValue(newValue)
  {
  }

  void operator()(Chan &chan)
  {
    chan.Channel = m_newValue;
  }

private:
  std::string m_newValue;
};


typedef ChanPtrLista::index<0>::type ChannelIndex;
ChannelIndex& channelIndex = multiIndex.get<0>();

ChannelIndex::iterator it = channelIndex.find("Old Channel Value");

// Set the new channel value!
channelIndex.modify(it, ChangeChannel("New Channel Value"));

You can find more information here.