5

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}

1 Answer 1

10

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.