sorting list

hello everyone,

I have std::vector<string> listItems
i want to remove duplicate values not changing the order of the strings
eg abc has "B","C","E","D","C"
I need "B","C","E","D" in the list


SOrt & erase are changing the order
std::sort(listItems.begin(), listItems.end());
listItems.erase(unique( listItems.begin(), listItems.end() ), listItems.end() );

Any help arreciated.
Thanks
Go through the vector, keeping track of what you've already seen. If you've already seen that value, erase it.

I haven't built or tested this code, but it should give you a rough idea. There are many many ways to do this; this code is just a simple, easy to understand demonstration. We just go through the vector, keeping track of values already seen, and if we've already seen it, erase from the vector.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
std::set<string> alreadySeen;
for (int i = 0 ; i < listItems.size() ; ++i)
{
  if (alreadySeen.find(listItems[i]) == alreadySeen.end())
  {
     // haven't seen this one before, 
     //  now we have seen it so add 
     //  it to the set of ones we've already seen
      alreadySeen.insert(listItems[i]);
  }
   else
  {
      // we have already seen this one, so erase this duplicate
      listItems.erase(listItems.begin() + i);
      i--; // we need to decrement i so that we will check the one we just moved into the space where the one that was erased used to be
  }
}

Last edited on
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
26
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;

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


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


int main()
{
   vector<string> V = { "B", "C", "D", "C", "E", "A", "B" };
   cout << "Before: " << V << endl;

   removeDuplicates( V );

   cout << "After:  " << V << endl;
}


Before: B C D C E A B 
After:  B C D E A 
Last edited on
Topic archived. No new replies allowed.