更改 std::set 以按 T 类型查找项目

Change std::set to find item by T type

本文关键字:类型 查找 项目 以按 std set 更改      更新时间:2023-10-16
template<class T>
class State {
    T state;
    double cost = 0;
    State<T> *cameFrom = nullptr;

我有这个模板类,我想创建一个std::set<State<T>>

类的<运算符返回this.cost < other.cost

类的==运算符返回this.state == other.state

假设我想检查State<T> x是否在一个集合中

我怎样才能使集合返回一个 iter !- end()(调用 set.find(x) ) 如果集合包含与 x 具有相同state(x.state)State<T>

std::set

关心operator==,它使用等价关系定义为具有与

bool equiv(T a, T b)
{
    if (a < b) return false;
    if (b < a) return false;
    return true;
}

如果您有State<T>值,state不同但cost相等,则只有一个可以进入您的std::set

您可能会在boost::multi_index_container上取得成功,您可以在其中按coststate查找内容

namespace bmi = boost::multi_index;
using state_set = boost::multi_index_container<State<T>, 
    bmi::indexed_by<
        bmi::ordered_unique<bmi::member<State<T>, double, &State<T>::cost>>,
        bmi::ordered_non_unique<bmi::member<State<T>, T, &State<T>::state>>
    >
>;
state_set set = ...;
auto & states_view = set.nth_index<1>();
if (auto it = states_view.find(x); it != states_view.end())
    ...