Erase element per key from multi_index_container with composite_key

左心房为你撑大大i 提交于 2019-12-11 18:24:21

问题


I have a multi_index_container with an index that is a composite_key. But I can not find a way to erase an element by its key. Please see below:

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/composite_key.hpp>

using namespace boost::multi_index;

struct Point
{
    int x, y;
};

void func()
{
  multi_index_container<Point,indexed_by<
    hashed_unique<
      composite_key<Point,
                    member<Point,int,&Point::x>,
                    member<Point,int,&Point::y> >
      > > > points;

  points.find( boost::make_tuple( 3, 3 ) );    // <- works
  points.erase( boost::make_tuple( 3, 3 ) );   // <- failes to compile
}

erase(key) works for indices that are not composite. But I am unable to find the correct syntax for composite keys.


回答1:


erasedoesn't have the type of overloads that allow for interoperation with tuples (technically, this relates to the concept of compatible extensions.) But you can have the same effect with a little more code:

auto p=points.equal_range(boost::make_tuple(3,3));
points.erase(p.first,p.second);



回答2:


Adding to the previous answer as per your request. You can have it like this:

Point p={3,3};
points.erase(points.key_extractor()(p));

The only problem with this is that it doesn't scale (if Point is expensive to construct.)



来源:https://stackoverflow.com/questions/12579000/erase-element-per-key-from-multi-index-container-with-composite-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!