DEV Community

dinhluanbmt
dinhluanbmt

Posted on

C++, erase all duplicate items/chars in vector or string

To remove all duplicate items/characters in a vector or string, we can use a combination of the std::remove and std::erase functions

string str = "this.is.string.with.dot";
//only removing the items not equal to '.' toward the begining of string
auto s_it = remove(str.begin(), str.end(), '.');  
str.erase(s_it, str.end()); // we need to erase it
cout << "str without dot  " << str << endl;

vector<int> iV{ 3,4,5,4,8,3,4,90,45,4,7 };
auto it = remove(iV.begin(), iV.end(), 4);
iV.erase(it, iV.end());
for (auto v : iV) {
    cout << " " << v;
}
cout << endl;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay