To remove duplicates from a vector in C++, you can use the std::sort
and std::unique
algorithms from the Standard Library, or you can use a std::unordered_set
to keep only unique elements.
In this example,
<vector>
, <unordered_set>
, and <iostream>
.vec
and initialize it with some integer values, including duplicates.std::unordered_set
named set
and initialize it with the elements of vec
. The unordered_set
only keeps unique elements.unique_vec
and initialize it with the elements of the set. This ensures that unique_vec
contains only unique elements from the original vector.#include <vector>
#include <unordered_set>
#include <iostream>
int main() {
std::vector<int> vec = {1, 2, 2, 3, 4, 4, 4, 5, 6, 6};
std::unordered_set<int> set(vec.begin(), vec.end());
std::vector<int> unique_vec(set.begin(), set.end());
std::cout << "Vector after removing all duplicates: ";
for (const int &val : unique_vec) {
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
Vector after removing all duplicates: 1 2 3 4 5 6
In this example,
<vector>
, <algorithm>
, and <iostream>
.vec
and initialize it with some integer values, including consecutive duplicates.std::sort
algorithm to sort the vector. This step is crucial because std::unique
only removes consecutive duplicates, so the vector must be sorted first.std::unique
algorithm to remove consecutive duplicates. This algorithm returns an iterator pointing to the new logical end of the vector.std::unique
by passing the iterator returned by std::unique
to the erase
method.#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> vec = {1, 2, 2, 3, 4, 4, 4, 5, 6, 6};
std::sort(vec.begin(), vec.end());
auto it = std::unique(vec.begin(), vec.end());
vec.erase(it, vec.end());
std::cout << "Vector after removing duplicates: ";
for (const int &val : vec) {
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
Vector after removing duplicates: 1 2 3 4 5 6
In this tutorial, we learned How to Remove Duplicates in a Vector in C++ language with well detailed examples.