我曾尝试搜索此内容,但未能真正找到合适的答案。我有一个 STL::set 我制作的自定义类。
类看起来像
class myObject{
public:
int a;
int b;
int c;
// constructor and operator < ()
}
< 比较基于b
和c
但我想在a
集合中查找元素。除了通过遍历集合并检查 myObject.a
来执行线性搜索之外,还有其他方法可以做到这一点吗?我正在尝试获取 myObject
的排序容器,但我需要能够通过标识符 a
找到该容器中的元素,而 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