这个问题已经在这里有一个答案:
- 如何找到特定的字段值的对象在一个std ::设置? 5个回答
我试图寻找这一点,但不能真正找到一个合适的回答。 我有一个STL ::设为我做了一个自定义类的。
这个类看起来像
class myObject{
public:
int a;
int b;
int c;
// constructor and operator < ()
}
在<比较基于b
和c
但我想找到通过集合中的元素a
。 有没有办法做到这一点除了执行由遍历集合并检查线性搜索myObject.a
? 我想获得的分类容器myObject
,但我需要能够通过该标识符,以查找该容器元素a
它是不是真正参与<比较。
您可以使用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