Search code examples
c++c++11stlstdset

Finding elements in std::set


Given that I have a std::set, how do I find out if one element of the set is before the other. For example, something like this -

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;
}

The above code does not work since <= is not defined for the bidirectional iterators, but how would one go about doing something like this?


Solution

  • A set orders its elements by operator< (by default). The comparator itself can be retrieved via key_comp or value_comp. So if both elements are in the set, the order is defined by the elements themselves - you don't need the iterators:

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

    If one or neither are in the set, then it depends on what you want to do in those cases:

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