Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete duplicates in vector (without sorting) C++

Tags:

c++

I have a vector that the user inputs some strings. I want to keep the order that the user inputs but delete any duplicate words. The only thing I could find online is sort and unique but since I cannot sort the vector I am stuck. Thank you in advance for any help.

e.x. input from user -> hello there dog cat hello cat book

vector should have -> hello there dog cat book

right now all I have is...

string s; 
vector <string> myVec; 

while (cin >> s){
 myVec.push_back(s); 
}

{code to sort vector}
like image 462
J.Doe Avatar asked Apr 20 '16 03:04

J.Doe


1 Answers

Alongside your vector, you can test whether the word is already in a std::set<std::string>, ignoring it if so, otherwise inserting it in both containers:

while (cin >> s)
    if (mySet.insert(s).second) // newly inserted in set?
        myVec.push_back(s);
like image 146
Tony Delroy Avatar answered Oct 23 '22 03:10

Tony Delroy