14

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;
markus
  • 143
  • 1
  • 4

2 Answers2

16

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;
    }
  }
}
leander
  • 8,527
  • 1
  • 30
  • 43
MSalters
  • 173,980
  • 10
  • 155
  • 350
0

Just to traverse, use const_iterators. If you want to modify values, use iterator.

Example:

typedef std::vector<int> IntVec;

IntVec vec;

// ...

IntVec::const_iterator iter_cur = vec.begin();
IntVec::const_iterator iter_end = vec.end();
while (iter_cur != iter_end) {
    int val = *iter_cur;
    // Do stuff with val here
    iter_cur++;
}
Vijay Mathew
  • 26,737
  • 4
  • 62
  • 93