在std :: set中查找元素

ssb*_*ssb 1 c++ stl stdset c++11

鉴于我有一个std::set,我如何找出该集合中的一个元素是否在另一个元素之前.例如,像这样的东西 -

bool before(const std::set &s, const int first, const int second) const {
  auto it_first = s.find(first);
  auto it_second = s.find(second);
  return it_first <= it_second;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码不起作用,因为<=没有为双向迭代器定义,但是如何做这样的事情呢?

Bar*_*rry 7

A setoperator<(默认情况下)对其元素进行排序.比较器本身可以通过key_comp或检索value_comp.因此,如果两个元素都在集合中,则顺序由元素本身定义 - 您不需要迭代器:

return s.key_comp()(first, second);
Run Code Online (Sandbox Code Playgroud)

如果一个或两个都不在集合中,那么它取决于您在这些情况下想要做什么:

if (s.count(first)) {
    if (s.count(second)) {
        return s.key_comp()(first, second);
    }
    else {
        /* no second */
    }
}
else {
    /* no first, possibly second */
}
Run Code Online (Sandbox Code Playgroud)