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)