Home Iterate over distinct pairs of a growing list
Reply: 0

Iterate over distinct pairs of a growing list

user1177 Published in June 19, 2018, 4:18 pm

Given a single list of n items (x1,x2,x3,...,xn), it is easy to iterate over all unique pairs in the list, i.e. (x1,x2), (x1,x3), ..., (x1,xn), (x2,x3), (x2,x4), ... ,(x2,xn),...,(x[n-1],xn). As a practical example, this could be an STL vector x, and iterate

for (auto i=0; i<n; i++) {
   for (auto j=i+1, j<n; j++) {
      // Do something with x[i],x[j]

My problem: what if the Do something part could grow the vector x, by adding one or even several elements. For example, after evaluating the loop for (x1,x2) the new length could be n+1 with a new element x[n+1]. Now I also want to, in the same loop, consider at some point the pairs (x1,x[n+1]),(x2,x[n+1]),...,(xn,x[n+1]). Is this possible, and if so, how?

I think two other pieces are: the order of evaluation doesn't matter (i.e. it doesn't matter when I get to consider pairs of x[n+1]) and it doesn't matter the order of the pairs (x[n+1],x1) or (x1,x[n+1]).


You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.370633 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO