To remove duplicates in a list in C++ using std::list, you can use the unique method followed by the erase method.
In this example,
numbers
with integer values.sort
method on the list to ensure duplicates are adjacent.unique
method on the list to remove consecutive duplicate elements.erase
method to remove the duplicate elements.#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main() {
list<int> numbers = {1, 2, 2, 3, 4, 4, 5};
numbers.sort();
numbers.unique();
for (auto num : numbers) {
cout << num << " ";
}
return 0;
}
1 2 3 4 5
In this example,
words
with string values.sort
method on the list to ensure duplicates are adjacent.unique
method on the list to remove consecutive duplicate elements.erase
method to remove the duplicate elements.#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main() {
list<string> words = {"apple", "banana", "cherry", "apple", "banana"};
words.sort();
words.unique();
for (auto word : words) {
cout << word << " ";
}
return 0;
}
apple banana cherry
In this tutorial, we learned How to Remove Duplicates in a List in C++ language with well detailed examples.