### Getting Results from the Set

Hi all,

 ``12345`` `````` std::set setx{ 100, 100 , 20}; for(auto &elem : setx) { cout<<"Print the set" << elem; }``````

Output : 20,100

But I want the result in the order we have inserted but
should not be any duplicates.

Result should be : 100,20

How to get this? Suggestions are appreciated.

Thank you,
Use a pair of containers - for instance, a vector in conjunction with a set - as suggested in this post:
https://stackoverflow.com/a/31943337

Or use a specialised container - for example, boost MultiIndex - as suggested in this post:
https://stackoverflow.com/a/64602237
A set has an ordering based on its content, not sequence of insertion. So you can't.

Use a different container (e.g. a vector) and de-duplicate that. A set may assist in that deduplication, provided the vector content has a natural ordering (as any numerical type will have).

 ``12345678910111213141516171819202122232425`` ``````#include #include #include #include using namespace std; template void deDuplicate( vector &V ) { set S; V.erase( remove_if( V.begin(), V.end(), [&S]( T e ){ return !S.insert( e ).second; } ), V.end() ); } template ostream & operator << ( ostream &out, const vector &V ) { for ( T e : V ) out << e << " "; return out; } int main() { vector V = { 1, 10, 9, 9, 10, 2, 1, 3, 4 }; cout << V << '\n'; deDuplicate( V ); cout << V << '\n'; }``````

 ```1 10 9 9 10 2 1 3 4 1 10 9 2 3 4```
Last edited on
@lastchance Thank you so much. It's working
Topic archived. No new replies allowed.