问题
I have tried searching for this but couldn't really find a proper answer. I have a stl::set of a custom class I made.
The class looks like
class myObject{
public:
int a;
int b;
int c;
// constructor and operator < ()
}
The < comparison is based on b and c but I want to find elements in the set by a. Is there a way to do that other than performing a linear search by iterating over the set and checking for myObject.a? I am trying to get a sorted container of myObject but I need to be able to find elements in that container by the identifier a which is not really involved in the < comparison.
回答1:
You can do it using boost::multi_index_container
class myObject
{
public:
int a;
int b;
int c;
bool operator < (const myObject& obj) const
{ return b < obj.b; }
};
using namespace boost::multi_index;
typedef multi_index_container<
myObject,
indexed_by<
ordered_unique<identity<myObject> >, // index by operator <
ordered_unique<member<myObject, int, &myObject::a> > // index by member a
>
> SetOfmyObjects;
typedef SetOfmyObjects::nth_index<0>::type SetIndex_b;
typedef SetOfmyObjects::nth_index<1>::type SetIndex_a;
...
SetOfmyObjects s;
const SetIndex_b& index_b = s.get<0>();
SetIndex_b::iterator it_b;
for (it_b = index_b.begin(); it_b != index_b.end(); ++it_b)
// ordered by b
const SetIndex_a& index_a = s.get<1>();
SetIndex_a::iterator it_a;
for (it_a = index_a.begin(); it_a != index_a.end(); ++it_a)
// ordered by a
来源:https://stackoverflow.com/questions/13202067/find-elements-in-stlsetobject-based-on-member-variable-of-object