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<typename Iter, typename Func>
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 <iostream>
#include <vector>
int main() {
std::vector<int> 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)