tags:

views:

114

answers:

2

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;
+1  A: 

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
+3  A: 

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 != foo.end(); /**/) {
       std::cout << *i << *j << std::endl;
    }
  }
}
MSalters
`auto` is not a part of current Standard.
Kirill V. Lyadvinsky
True, laziness here. Comment added.
MSalters
Neat! You're in 1x mode already!
xtofl
Actually, probably cleaner to use TAD for it.
MSalters