查找std::set中的元素

Finding elements in std::set

本文关键字:元素 set std 查找      更新时间:2023-10-16

假设我有一个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;
}

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

A setoperator<排序(默认)。比较器本身可以通过key_compvalue_comp检索。因此,如果两个元素都在集合中,则顺序由元素本身定义—不需要迭代器:

return s.key_comp()(first, second);

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

if (s.count(first)) {
    if (s.count(second)) {
        return s.key_comp()(first, second);
    }
    else {
        /* no second */
    }
}
else {
    /* no first, possibly second */
}

如果你想寻找比std::set更通用的解决方案,这个方法将适用于任何具有forward迭代器的容器:

template <class T>
bool before( const T &cont, typename T::const_iterator first, typename T::const_iterator second )
{
    for( auto it = cont.begin(); true; ++it ) {
        if( it == first ) return true;
        if( it == second ) return false;
    }
 }

假设firstsecond是有效的迭代器。现在您可以为std::setstd::map提供更优的专门化:

return cont.key_comp()( *first, *second );

,对于具有随机访问迭代器的容器:

return first < second;