Removing duplicates from a sorted vector in C++ can be efficiently achieved using the std::unique()
algorithm from the <algorithm>
 header.
The std::unique()
function removes consecutive duplicate elements and returns an iterator to the new end of the range.
After using std::unique()
, you need to resize the vector to remove the extra elements.
Here’s how you can do it:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers{1, 2, 2, 3, 4, 4, 5};
// Removing duplicates
auto new_end = std::unique(numbers.begin(),
numbers.end());
// Resizing the vector
numbers.erase(new_end, numbers.end());
// Printing the result
for (const int& num : numbers) {
std::cout << num << " ";
}
}
1 2 3 4 5
<algorithm>
header to access the std::unique()
function.std::unique()
: The std::unique()
function modifies the vector in-place and removes consecutive duplicates. It returns an iterator pointing to the element that should be considered the new end of the vector.std::unique()
, the vector still contains the old elements beyond the new logical end. You must call erase()
to remove these elements physically.std::unique()
for this method to work correctly. If the vector is not sorted, you can sort it using std::sort()
.Combining Steps: If the vector is not already sorted, you can combine the steps of sorting and removing duplicates:
std::sort(numbers.begin(), numbers.end());
auto new_end = std::unique(numbers.begin(),
numbers.end());
numbers.erase(new_end, numbers.end());
Using with Custom Types: If you are working with a vector of custom objects, ensure your type supports equality comparison or provide a custom comparator to std::unique()
.
Removing duplicates from a sorted vector is a common task in C++, and using std::unique()
along with std::erase()
provides a clean and efficient solution.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to iterator and range-based algorithms, using examples from the standard library