Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over all pairs of elements in std-containers (C++)

Tags:

c++

iterator

stl

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;
like image 839
markus Avatar asked Dec 01 '09 08:12

markus


1 Answers

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;
    }
  }
}
like image 79
MSalters Avatar answered Sep 30 '22 04:09

MSalters