How to get unique value pairs from a set of stl

I have a stl set of integers, and I would like to iterate over all unique pairs of integer values, where by uniqueness I consider val1, val2 and val2, val1 to be the same, and I should see this combination once.

I wrote this in python, where I use list index (clusters):

for i in range(len(clusters) - 1): for j in range(i+1,len(clusters)): #Do something with clusters[i],clusters[j]) 

but without an index, I'm not sure how I can achieve the same with a set of stl and iterators. I tried:

 for (set<int>::iterator itr = myset.begin(); itr != myset.end()-1; ++itr) { cout << *itr; } 

but this is not so, since the iterator does not have the operator a.

How can I achieve this or use a different container?

+4
source share
3 answers

How about something in the following lines:

 for(set<int>::const_iterator iter1 = myset.begin(); iter1 != myset.end(); ++iter1) { for(set<int>::const_iterator iter2 = iter1; ++iter2 != myset.end();) { { std::cout << *iter1 << " " << *iter2 << "\n"; } } 

This gives all N*(N-1)/2 unique pairs, where N is the number of integers in your set.

Aside: use const_iterator whenever you iterate over a container without changing anything, this is a good style and may have better performance.

EDIT: Changed the code to reflect the proposal made by Steve Jessop.

+8
source

You do not need to do end() - 1 , since end() is an iterator that points after the last element in the container.

Corrected Code:

 for (set<int>::iterator itr = myset.begin(); itr != myset.end(); ++itr) { for (set<int>::iterator itr2 = itr + 1; itr2 != myset.end(); ++itr2) { // Do whatever you want with itr and itr2 } } 
+2
source

Put your data in boost :: bimap and then iterate in both directions, copy the results to a standard STL map, which will ensure uniqueness.

-1
source

All Articles