CKTIS / C++
std::unique — removing consecutive duplicates
std::unique keeps the first element of each consecutive group of equivalent elements. It returns the new logical end of the range without reducing the container's size.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <algorithm>
std::unique(first, last);
std::unique(first, last, pred);std::unique, declared in <algorithm>, processes [first, last), keeping the first element of each consecutive group of equivalent values. It preserves the order of retained elements. By default it compares using ==; the overload accepting pred uses a custom equivalence predicate.
The result newEnd is an iterator past the last retained element. The meaningful result occupies [first, newEnd). The container size stays unchanged, and values in [newEnd, last) are unspecified, although the objects remain valid. For std::vector, follow with values.erase(newEnd, values.end()) to physically remove that tail.
The algorithm does not remove duplicates globally: the second 1 in the example survives because 2 separates it from the earlier group. Sorting first can group equal values, but changes their order; std::unique itself does not require sorted input.
Iterators must meet forward-iterator requirements, and elements must support move assignment. The comparison relation must be reflexive, symmetric, and transitive; pred must not modify the compared elements. For a nonempty range of length N, the algorithm performs exactly N - 1 comparisons. For an empty range, it returns last.
Examples
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> values{1, 1, 2, 2, 1, 3, 3};
auto newEnd = std::unique(values.begin(), values.end());
values.erase(newEnd, values.end());
for (std::size_t i = 0; i < values.size(); ++i) {
if (i != 0) std::cout << ' ';
std::cout << values[i];
}
std::cout << '\n';
}
Result
1 2 1 3
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.