Search code examples
c++unordered-set

How to iterate on unordered pairs inside an unordered_set?


What's a concise way to iterate on unordered-pairs of elements in unordered_set?

(So order doesn't matter and elements should be different)

e.g. {1, 2, 3} => (1, 2) (2, 3) (1, 3)

My initial attempts were something like

for (i = 0; i < size - 1; i++) {
  for (j = i + 1; j < size; j++) {
    ...
  }
}

But that's not super-convenient with iterators.


Solution

  • This should work, given an std::unordered_set s:

    auto set_end = s.end();
    for (auto ai = s.begin(); ai != set_end; ++ai) {
        for (auto bi = std::next(ai); bi != set_end; ++bi) {
            // *ai, *bi
        }
    }
    

    This is basically the iterator equivalent of the following in integers:

    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j < n; ++j) {
            // i, j
        }
    }