Mastering C++ std::unique: Common Pitfalls and Alternatives

2025-09-06

First, let's clarify what std::unique actually does. It's a bit of a misnomer. std::unique doesn't remove elements from a container. Instead, it rearranges the elements in a range so that all unique elements are moved to the beginning. It then returns an iterator to the end of this new, "unique" portion of the range. The elements after this returned iterator are left in an unspecified but valid state.

The key thing to remember is that std::unique only works on consecutive duplicates. So, you'll almost always see it used on a sorted range.

Here's the basic usage

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 2, 3, 3, 3, 4, 5, 5};
    
    // std::unique requires a sorted range for all duplicates to be consecutive.
    // If the data isn't sorted, it won't work as expected.
    
    auto last = std::unique(numbers.begin(), numbers.end());
    
    // Now, 'last' points to the first duplicate.
    // The vector is now {1, 2, 3, 4, 5, ?, ?, ?, ?}
    
    // To actually remove the elements, you must use erase.
    numbers.erase(last, numbers.end());
    
    for (int n : numbers) {
        std::cout << n << " ";
    }
    std::cout << std::endl; // Output: 1 2 3 4 5 
    
    return 0;
}

This is the most frequent mistake. If your range isn't sorted, std::unique will only remove consecutive duplicates, not all duplicates.

// Problematic Code
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 4, 2, 3, 4, 5, 5};
    
    // The '2's and '4's are not consecutive.
    // The duplicates at the end will be handled, but not the others.
    auto last = std::unique(numbers.begin(), numbers.end());
    
    for (int n : numbers) {
        std::cout << n << " ";
    }
    std::cout << std::endl; // Output: 1 2 4 2 3 4 5 5 (or similar, unspecified)
    
    return 0;
}

Solution
Always std::sort your range before calling std::unique. This ensures all duplicate values are next to each other.

// Correct Usage
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 4, 2, 3, 4, 5, 5};
    
    std::sort(numbers.begin(), numbers.end());
    
    // Now the vector is sorted: {1, 2, 2, 3, 4, 4, 5, 5}
    auto last = std::unique(numbers.begin(), numbers.end());
    
    numbers.erase(last, numbers.end());
    
    for (int n : numbers) {
        std::cout << n << " ";
    }
    std::cout << std::endl; // Output: 1 2 3 4 5
    
    return 0;
}

As we've mentioned, std::unique doesn't resize the container. If you just call std::unique and then iterate over the entire original container, you'll still see the "junk" values at the end.

// Problematic Code
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 2, 3, 3, 3, 4, 5, 5};
    
    auto last = std::unique(numbers.begin(), numbers.end());
    
    // This loops over the whole original vector.
    for (int n : numbers) {
        std::cout << n << " ";
    }
    std::cout << std::endl; // Output: 1 2 3 4 5 5 5 5 5 (or similar)
    
    return 0;
}

Solution
Always follow up std::unique with a call to erase using the iterator it returns. This is so common that it's often referred to as the "unique-erase idiom".

// Correct Usage
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 2, 3, 3, 3, 4, 5, 5};
    
    auto last = std::unique(numbers.begin(), numbers.end());
    
    numbers.erase(last, numbers.end());
    
    for (int n : numbers) {
        std::cout << n << " ";
    }
    std::cout << std::endl; // Output: 1 2 3 4 5
    
    return 0;
}

Sometimes, the sort and unique approach isn't ideal, especially if you need to maintain the original order of the elements or if the overhead of sorting is too high. Here are some excellent alternatives.

std::set and std::unordered_set are containers that by definition only store unique elements. This is a great alternative if you don't need to maintain a vector or if the order doesn't matter (in which case unordered_set is often faster).

#include <iostream>
#include <vector>
#include <set>

int main() {
    std::vector<int> numbers = {1, 2, 4, 2, 3, 4, 5, 5};
    
    // A std::set automatically handles uniqueness and sorting.
    std::set<int> unique_numbers(numbers.begin(), numbers.end());
    
    // To get the data back into a vector, you can do this:
    std::vector<int> result(unique_numbers.begin(), unique_numbers.end());
    
    for (int n : result) {
        std::cout << n << " ";
    }
    std::cout << std::endl; // Output: 1 2 3 4 5
    
    return 0;
}

Pros

Simple
The code is very clean and easy to read.

Efficient
Insertion and uniqueness checks are very fast.

Cons

Order Lost
Using std::unordered_set will not preserve the original order of elements. std::set will sort them.

Extra Memory
This approach requires creating a new container, which can be a concern for very large datasets.

For C++11 and later, you can use std::stable_partition with a lambda function and a std::unordered_set to remove duplicates while preserving the original relative order.

#include <iostream>
#include <vector>
#include <unordered_set>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 4, 2, 3, 4, 5, 5};
    std::unordered_set<int> seen;
    
    // We partition the vector. Elements we've seen go to the end.
    auto unique_end = std::stable_partition(numbers.begin(), numbers.end(),
        [&seen](int val) {
            // If we can insert it, it's a new unique element.
            return seen.insert(val).second;
        });
        
    numbers.erase(unique_end, numbers.end());
    
    for (int n : numbers) {
        std::cout << n << " ";
    }
    std::cout << std::endl; // Output: 1 2 4 3 5
    
    return 0;
}

Pros

Preserves Order
This is the key advantage. The relative order of the first occurrence of each element is maintained.

In-place
Like std::unique, this modifies the container in-place, avoiding extra memory allocation.

Cons

More Complex
The code is a bit more intricate due to the use of a lambda and a std::unordered_set as a helper.

Performance
While better than std::unique for unsorted ranges (if you don't care about sorting), it can have higher overhead than a simple std::sort followed by std::unique on small to medium-sized datasets.


cpp



C++ Scope: A Friendly Guide to Avoiding Pitfalls

One of the most frequent issues is when a variable in an inner scope "shadows" or hides a variable with the same name in an outer scope


Beyond Simple Strings: Advanced Path Component Extraction with C++'s stem()

The stem() function essentially gives you the filename without the final extension. Think of it as stripping off the last part that starts with a dot (.)


C++ Ranges: Common Issues with inplace_merge and How to Fix Them

The most frequent problem with std::ranges::inplace_merge is that it assumes the two sub-ranges you're merging are already sorted



Moving C++ I/O Streams: Pitfalls and Best Practices

Misunderstanding its purpose Many developers assume this operator can be used for copying stream objects. It can't! Streams like std::ifstream or std::ofstream manage external resources (like open files), and copying them would lead to two objects trying to control the same file


Navigating Chunks: C++ std::ranges::chunk_view Outer-Iterator Deep Dive

Here is a friendly explanation of common issues and alternatives for this iterator.Imagine you have a big list of numbers


C++ fsetpos: Common Pitfalls and Modern Alternatives

std::fsetpos is a function in C++ (inherited from C's <cstdio>) used to set the file position indicator for a stream. It works in tandem with std::fgetpos


Troubleshooting std::forward_list::begin() in C++

The std::forward_list::begin() method is a fundamental part of the C++ Standard Template Library (STL). It returns an iterator that points to the first element of a std::forward_list


The C++23 Enumerate View: Simplifying Indexing in Ranges

The std::ranges::enumerate_view (which you typically create using the range adaptor std::views::enumerate) is a way to iterate over a range while also getting the zero-based index of each element


Efficiently Handling C++ split_view: A Guide to Best Practices

The std::ranges::split_view::base() method is a simple but crucial part of the C++20 Ranges library. Its purpose is to get the underlying base range that the split_view is operating on


Simplifying C++ with std::list Deduction Guides

Deduction guides, introduced in C++17, are a powerful feature that allows the compiler to deduce the template arguments for a class template from the arguments used in its constructor