Unique Function in String in C++? Explained

Formulas & functions · Updated November 23, 2026

The unique function in C++ is not a single function but a family of std::unique algorithms that remove consecutive duplicate elements from a range, commonly applied to strings to eliminate repeated characters. For a string, std::unique returns an iterator to the new end of the string after removing adjacent duplicates, and you typically call erase with that iterator to actually resize the string.

What Does std::unique Do Exactly?

std::unique is an algorithm in the <algorithm> header. It operates on a range defined by two iterators (e.g., str.begin() and str.end()) and removes consecutive duplicate elements. It does not remove all duplicates—only those that are adjacent. For example, given the string "aabbcc", std::unique will transform it to "abc" (plus leftover characters at the end that are ignored after erasing). But given "abca", it will leave it unchanged because no two adjacent characters are equal.

The function returns an iterator pointing to the new logical end of the range. The elements after that iterator are still physically present in the container but are considered “removed” and should be erased to actually free the space.

How to Use std::unique with Strings

To remove consecutive duplicate characters from a string, you combine std::unique with the string’s erase member function. Here is a complete example:

#include <iostream>
#include <algorithm>
#include <string>

int main() {
    std::string s = "aabbccddee";
    auto new_end = std::unique(s.begin(), s.end());
    s.erase(new_end, s.end());
    std::cout << s << '\n';  // Output: abcde
    return 0;
}

After std::unique, new_end points to the character after the last unique element. The erase call removes everything from that point to the end, leaving s as "abcde".

Custom Comparison and Removing Duplicates with Predicates

std::unique has an overload that accepts a binary predicate to define what counts as a duplicate. For example, you could remove consecutive characters that are equal ignoring case:

#include <iostream>
#include <algorithm>
#include <string>
#include <cctype>

bool same_ignore_case(char a, char b) {
    return std::tolower(static_cast<unsigned char>(a)) ==
           std::tolower(static_cast<unsigned char>(b));
}

int main() {
    std::string s = "AaBbCc";
    auto new_end = std::unique(s.begin(), s.end(), same_ignore_case);
    s.erase(new_end, s.end());
    std::cout << s << '\n';  // Output: ABC (or Aa? Actually removes consecutive case-insensitive duplicates)
    return 0;
}

In this example, "Aa" are consecutive and case-insensitively equal, so the first 'A' is kept and the second 'a' is removed, resulting in "ABC" (since the original was 'A','a','B','b','C','c'). The predicate should be a binary function that returns true if the two elements are considered duplicates.

Common Pitfalls and Misconceptions

One common mistake is forgetting to call erase after std::unique. Without it, the string still has its original size, and the leftover characters remain, which can cause confusion. Another misconception is that std::unique removes all duplicates in the string—it only removes consecutive ones. If you want to remove all duplicate characters (not just adjacent), you need a different approach, such as sorting the string first (which changes order) or using a set to track seen characters.

Also note that std::unique works on any forward iterator range, not just strings. It is a generic algorithm, so it works on std::vector, arrays, and other containers.

Performance and Complexity

std::unique runs in linear time—O(n) where n is the number of characters in the string. It makes exactly one pass over the range, comparing adjacent elements. The space complexity is O(1) because it does not allocate extra memory; it rearranges elements in place. This makes it very efficient for large strings.

Alternatives to std::unique for Strings

If you need to remove all duplicate characters (not just consecutive), you have several options:

  • Using a set: Iterate through the string and insert characters into an std::unordered_set to keep track of seen characters, then build a new string from the first occurrence of each character.
  • Sorting first: Sort the string, then apply std::unique and erase. This removes all duplicates but changes the original order.
  • Manual loop with a boolean array: For ASCII strings, you can use a bool[256] to mark seen characters and build a result string.

Each method has trade-offs in time and space. The set approach is O(n) average time but uses O(k) extra space (k = number of distinct characters). Sorting is O(n log n) and may not preserve order.

Frequently Asked Questions

Q: Does std::unique work with std::string in C++11?
A: Yes, std::unique has been available since C++98 and works with any standard container that provides forward iterators, including std::string in all C++ versions.

Q: Why does my string still have the same length after calling std::unique?
A: Because std::unique only rearranges elements and returns an iterator to the new end; it does not resize the container. You must call erase with that iterator to actually truncate the string.

Q: Can I use std::unique to remove duplicate words in a vector of strings?
A: Yes, but only if the duplicates are adjacent. If you want to remove all duplicate words regardless of order, you need to sort the vector first (or use a set).

Q: What is the difference between std::unique and std::unique_copy?
A: std::unique modifies the original range in place, while std::unique_copy copies the unique elements to a new range without modifying the original.

Q: Is std::unique stable (preserves the relative order of remaining elements)?
A: Yes, std::unique preserves the relative order of the elements that remain. It only removes duplicates, never reorders anything else.

Summary

In summary, the “unique function” for strings in C++ is std::unique, which removes consecutive duplicate characters. Always pair it with erase to actually resize the string. For non-consecutive duplicates, use a different algorithm. Remember to include <algorithm> and <string> headers. With this understanding, you can efficiently clean up strings in your C++ programs.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.