Getting Results from the Set

Hi all,

1
2
3
4
5
  std::set<int> 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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;

template<typename T> void deDuplicate( vector<T> &V )
{
   set<T> S;
   V.erase( remove_if( V.begin(), V.end(), [&S]( T e ){ return !S.insert( e ).second; } ), V.end() );
}

template<typename T > ostream & operator << ( ostream &out, const vector<T> &V )
{
   for ( T e : V ) out << e << " ";
   return out;
}

int main()
{
   vector<int> 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.