HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Using standard library to simplify pairwise iteration of container values

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
containerstandarditerationsimplifyusinglibraryvaluespairwise

Problem

I came up with this code whilst answering this question.

Is there a simpler way of doing this using standard library?

I want to iterate over every object and do something with every other object.

For example, 4 values 1, 2, 3, 4 would pair like:

(1, 2), (1, 3), (1, 4)
(2, 3), (2, 4)
(3, 4)


Each value combines with every other value. None combine with themselves, and symmetric pairings are considered the same.

This might be useful in a collision system where you want to check every solid with every other.

template
void pair_wise(Iter it, Iter last, Func func) {
    while(it != last) {
        Iter other = it;
        ++other;
        while(other != last) {
            func(*it, *other);
            ++other;
        }
        ++it;
    }
}


Usage:

#include 
#include 

int main() {
    std::vector values = {1, 2, 3, 4};

    pair_wise(values.begin(), values.end(),
              [](int& lhs, int& rhs) {
                  std::cout << "(" << lhs << ", " << rhs << ")\n";
              });                  
}


Output:

(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

Solution

It would be possible to write as for_each call to a functor writing for_each again, but I don't think it would actually be shorter.

I don't think pair_wise is a good name. There are two many things that it could mean. I'd suggest something with combinations as it calls the function for all 2-combinations.

Context

StackExchange Code Review Q#23262, answer score: 5

Revisions (0)

No revisions yet.