What's the best way to iterate over all pairs of elements in std container like std::list
, std::set
, std::vector
, etc.?
Basically to do the equivalent of this, but with iterators:
for (int i = 0; i < A.size()-1; i++)
for(int j = i+1; j < A.size(); j++)
cout << A[i] << A[j] << endl;
The easiest way is just rewriting the code literally:
for (auto i = foo.begin(); i != foo.end(); ++i) {
for (auto j = i; ++j != foo.end(); /**/) {
std::cout << *i << *j << std::endl;
}
}
Replace auto
with a const_iterator for C++98/03. Or put it in its own function:
template<typename It>
void for_each_pair(It begin, It end) {
for (It i = begin; i != end; ++i) {
for (It j = i; ++j != end; /**/) {
std::cout << *i << *j << std::endl;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With