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

时间:2019-01-09 11:31:46

标签: c++ templates stdset

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是否在集合中

如果集合包含一个set.find(x)State<T>相同的state(x.state),我该如何使集合返回iter!-end()(调用x) ?

1 个答案:

答案 0 :(得分:0)

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())
    ...