c++ - 根据object的成员变量查找STL::set<object>中的元素

标签 c++ stl set

<分区>

我曾尝试搜索此内容,但未能真正找到合适的答案。我有一个 STL::set 我制作的自定义类。

类看起来像

class myObject{

public:
  int a;
  int b;
  int c;

// constructor and operator < ()
}

< 比较基于bc 但我想在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

关于c++ - 根据object的成员变量查找STL::set<object>中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13202067/

相关文章:

c++ - 如何使用 time.h 获取 UTCTime 中秒的小数部分

c++ - 我的一些函数出现 "undefined reference"错误,我不知道为什么

c++ - React Native 0.59 应用程序因 libc 错误而崩溃

c++ - Clion 调试 : How to step into STL

python - 如何删除字典中的键值?

java - 为什么java "putAll"无法深复制Map的值元素?

python - 使用正则表达式查询集合

c++ - 错误 : invalid conversion from ‘void*’ to ‘test::apr_size_t* {aka long unsigned int*}’ [-fpermissive]

c++ - 如何序列化并通过网络发送 std::list?

c++ - 在 vector 中找到最近的点