The Wayback Machine - https://web.archive.org/web/20241119192551/https://www.geeksforgeeks.org/stdunique-in-cpp/
Open In App

std::unique in C++

Last Updated : 11 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, std::unique is used to remove duplicates of any element present consecutively in a range[first, last). It performs this task for all the sub-groups present in the range having the same element present consecutively.

  • It does not delete all the duplicate elements, but it removes duplicacy by just replacing those elements with the next element present in the sequence which is not duplicate to the current element being replaced. All the elements which are replaced are left in an unspecified state.
  • Another interesting feature of this function is that it does not change the size of the container after deleting the elements, it just returns a pointer pointing to the new end of the container, and based on that we have to resize the container or remove the garbage elements.

Time Complexity: O(N)
Space Complexity: O(1)

Usage of std::unique in C++

The std::unique can be used in two ways as shown below:

  • For Comparing elements using ==
  • For Comparing using a pre-defined function

1. Comparing elements using ==:

Syntax:

 ForwardIterator unique (ForwardIterator first, ForwardIterator last, BinaryPredicate Pred);

Here, the first and last are the same as the previous case.

Pred: Binary function that accepts two elements in the range as argument, and returns a value convertible to bool. The value returned indicates whether both arguments are considered equivalent(if true, they are equivalent and one of them is removed). The function shall not modify any of its arguments. This can either be a function pointer or a function object.

Return Value: It returns an iterator to the element that follows the last element not removed. The range between the first and this iterator includes all the elements in the sequence that were not duplicates and hence not removed.

Below is the implementation of the above method:

C++




// C++ program to demonstrate the use of std::unique
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> v = { 1, 1, 3, 3, 3, 10, 1, 3, 3, 7, 7, 8 };
 
    vector<int>::iterator ip;
 
    // Using std::unique
    ip = std::unique(v.begin(), v.begin() + 12);
    // Now v becomes {1 3 10 1 3 7 8 * * * * *}
    // * means undefined
 
    // Resizing the vector so as to remove the undefined
    // terms
    v.resize(std::distance(v.begin(), ip));
 
    // Displaying the vector after applying std::unique
    for (ip = v.begin(); ip != v.end(); ++ip) {
        cout << *ip << " ";
    }
 
    return 0;
}


Output

1 3 10 1 3 7 8 

Here, in this vector, all the sub-groups having consecutive duplicate elements has been reduced to only one element. Note that it doesnot matter whether the same element is present later on as well, only duplicate elements present consecutively are handled by this function.

2. Comparing using a pre-defined function:

Syntax:

ForwardIterator unique (ForwardIterator first, ForwardIterator last);

first: Forward iterator to the first element in the container.
last: forward iterator to the last element in the container.

Return Value: It returns an iterator to the element that follows the last element not removed. The range between first and this iterator includes all the elements in the sequence that were not duplicates and hence not removed.

Below is the implementation of the above method:

C++




// C++ program to demonstrate the use of std::unique
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
 
// Defining the BinaryFunction
bool Pred(char a, char b)
{
    // Checking if both the arguments are same and equal
    // to 'G' then only they are considered same
    // and duplicates are removed
    if (a == b && a == 'G') {
        return 1;
    }
    else {
        return 0;
    }
}
int main()
{
    // Declaring a string
    string s = "You arre vvvisiting GGGGFGGGG";
 
    // Using std::unique to remove the consecutive
    // G in the word
    auto ip = std::unique(s.begin(), s.end(), Pred);
 
    // Displaying the corrected string
    cout << string(s.begin(), ip);
    return 0;
}


Output

You arre vvvisiting GFG

Here, we have manipulated the binary function in such a way that only if two G are passed as arguments, then only they will be considered as same, and if any other character is present consecutively, then it will remain unaffected, and will not be removed (like r in arre, v in visiting).

Interesting Point:

The std::unique function can be used in combination with the std::erase function to remove consecutive duplicate elements from a sorted container.

vec.erase(unique(vec.begin(), vec.end()), vec.end());

Where std::unique can be used?

1. Remove all the duplicate elements from a container:

Many of you must have searched for std::unique with a view that it will remove all the duplicate elements from the container, and now you might feel a bit disappointed to know that it removes only the consecutive duplicate elements. But, although, std::unique cannot do so as per its definition, but applying a bit of logic, we can make that happen. What we need to do is just sort the array before applying std::unique, such that all equal elements become consecutive, and now we have std::unique to remove all the duplicate consecutive elements. So, std::unique can also be used to remove all the duplicate elements from a container.

Below is the implementation of the above method:

C++




// C++ program to demonstrate the use of std::unique
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> v = { 1, 2, 3, 3, 3, 10, 1, 2, 3, 7, 7, 8 };
 
    vector<int>::iterator ip;
 
    // Sorting the array
    std::sort(v.begin(), v.end());
    // Now v becomes 1 1 2 2 3 3 3 3 7 7 8 10
 
    // Using std::unique
    ip = std::unique(v.begin(), v.begin() + 12);
    // Now v becomes {1 2 3 7 8 10 * * * * * *}
    // * means undefined
 
    // Resizing the vector so as to remove the undefined
    // terms
    v.resize(std::distance(v.begin(), ip));
 
    // Displaying the vector after applying std::unique
    for (ip = v.begin(); ip != v.end(); ++ip) {
        cout << *ip << " ";
    }
 
    return 0;
}


Output

1 2 3 7 8 10 

Explanation:

Firstly, we sorted the array such that all the equal duplicate elements become consecutive and now applying std::unique to it such that the duplicacy is removed, and in this way we remove all the duplicate elements from a container, whether consecutive or not.

Count unique elements: It can also be used if we want to count the total no. of unique elements in a container.

C++




// C++ program to demonstrate the use of std::unique
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
    vector<int> v = { 1, 1, 3, 3, 3, 10, 1, 3, 3, 7, 7, 8 };
 
    vector<int>::iterator ip;
 
    int count;
    sort(v.begin(), v.end());
 
    // Using std::unique and std::distance to count
    // unique elements in a container
    count = std::distance(
        v.begin(), std::unique(v.begin(), v.begin() + 12));
 
    // Displaying the value of count
    cout << "Total no. of unique elements = " << count;
 
    return 0;
}


Output

Total no. of unique elements = 5

Explanation:

As we know that std::unique returns an iterator to what should be the new end of the container after removing duplicate elements, so just counting the total no. of elements from beginning till this new end with the help of std::distance, should give us the total no. of unique elements in the container.



Previous Article
Next Article

Similar Reads

std::fixed, std::scientific, std::hexfloat, std::defaultfloat in C++
Formatting in the standard C++ libraries is done through the use of manipulators, special variables or objects that are placed on the output stream. There are two types of floating point manipulators namely, fixed floating point and scientific floating point. These all are defined in header <iostream>. Use of precision : In the default floati
3 min read
std::oct , std::dec and std::hex in C++
This function is used to set the base to octal, decimal or hexadecimal. It sets the basefield format flag for the str stream to the specified base std::oct : When basefield is set to octal, integer values inserted into the stream are expressed in octal base (i.e., radix 8). For input streams, extracted values are also expected to be expressed in oc
2 min read
std::string::length, std::string::capacity, std::string::size in C++ STL
Prerequisite: String in C++ String class is one of the features provided by the Standard template library to us, So it comes up with great functionality associated with it. With these Functionalities, we can perform many tasks easily. Let's see a few of the functionalities string class provides. Header File <string> String Functionalities The
6 min read
std::stod, std::stof, std::stold in C++
std::stod() : It convert string into double. Syntax: double stod( const std::string& str, std::size_t* pos = 0 ); double stod( const std::wstring& str, std::size_t* pos = 0 ); Return Value: return a value of type double Parameters str : the string to convert pos : address of an integer to store the number of characters processed. This param
3 min read
std::setbase, std::setw , std::setfill in C++
The useful input/output manipulators are std::setbase, std::setw and std::setfill. These are defined in and are quite useful functions. std::base : Set basefield flag; Sets the base-field to one of its possible values: dec, hex or oct according to argument base.Syntax : std::setbase (int base);decimal : if base is 10hexadecimal : if base is 16octal
3 min read
std::istream_iterator and std::ostream_iterator in C++ STL
The STL is a very powerful library in C++. It is strongly built on the principles of template programming. The STL library has three main components : Containers: These classes define the data structures which are used to contain the data. The data may be stored in linked lists, or trees or arrays. The containers provided in the STL are vector, deq
6 min read
Difference between std::swap and std::vector::swap
The std::swap is a general function used to exchange the given values whereas the std::vector::swap is a specialized function that can swap all the contents of two different vector containers.Below are some major key differences between std::swap and std::vector::swap, std::swapstd::vector::swapThe std::swap() is a built-in function in C++ STL whic
3 min read
std::bitset::to_ullong and std::bitset::to_ulong in C++ STL
Bitset: A bitset is an array of bool but each Boolean value is not stored separately instead bitset optimizes the space such that each bool takes 1 bit space only, so space taken by bitset bs is less than that of bool bs[N] and vector bs(N). However, a limitation of bitset is, N must be known at compile time, i.e., a constant (this limitation is no
2 min read
std::string::remove_copy(), std::string::remove_copy_if() in C++
remove_copy() It is an STL function in c++ which is defined in algorithm library. It copies the elements in the range [first, last) to the range beginning at result, except those elements that compare equal to given elements. The resulting range is shorter than [first,last) by as many elements as matches in the sequence, which are "removed". The re
4 min read
Difference between std::quick_exit and std::abort
std::quick_exit() It Causes normal program termination to occur without completely cleaning the resources. Syntax : void quick_exit(int exit_code) no except; In case of execution of threads the codes becomes complex and knowing the execution of threads is hard. While one the thread might be waiting for a process to end while the other thread is wai
3 min read
Difference between std::set::lower_bound and std::lower_bound in C++
Prerequisite: Random-access Iterators in C++, Bidirectional Iterators in C++. std::lower_bound in C++: The lower_bound() method in C++ is used to return an iterator pointing to the first element in the range [first, last) which has a value not less than the given value. This means that the function returns the index of the next smallest number just
4 min read
Difference between std::set::upper_bound and std::upper_bound in C++
Prerequisites: Random-access Iterators, Bidirectional Iterators Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. Functions
4 min read
std::tuple_element() and std::tuple_size() in C++ with Examples
A tuple is an object that can hold a number of elements. The elements can be different data types. The elements of tuples are initialized as arguments in the order in which they will be accessed. The functions- tuple_element() and tuple_size() are only defined for elements using tuple_like interface. tuple_element():The C++ function tuple_element(a
2 min read
std::tuple, std::pair | Returning multiple values from a function using Tuple and Pair in C++
There can be some instances where you need to return multiple values (maybe of different data types ) while solving a problem. One method to do the same is by using pointers, structures or global variables, already discussed here There is another interesting method to do the same without using the above methods,  using tuples (for returning multipl
2 min read
std::regex_match, std::regex_replace() | Regex (Regular Expression) In C++
Regex is the short form for “Regular expression”, which is often used in this way in programming languages and many different libraries. It is supported in C++11 onward compilers.Function Templates used in regex regex_match() -This function return true if the regular expression is a match against the given string otherwise it returns false. C/C++ C
3 min read
std::minmax() and std::minmax_element() in C++ STL
C++ defined functions to get smallest and largest elements among 2 or in a container using different functions. But there are also functions that are used to get both smallest and largest element using a single function, "minmax()" function achieves this task for us. This function is defined in "algorithm" header file. This article would deal in it
4 min read
std::string::replace_copy(), std::string::replace_copy_if in C++
replace_copy replace_copy() is a combination of copy() and replace(). It copies the elements in the range [first, last) to the range beginning at result, replacing the appearances of old_value by new_value.The range copied is [first, last), which contains all the elements between first and last, including the element pointed by first but not the el
4 min read
std::string::append vs std::string::push_back() vs Operator += in C++
To append characters, you can use operator +=, append(), and push_back(). All of them helps to append character but with a little difference in implementation and application. Operator += : appends single-argument values. Time complexity : O(n)append() : lets you specify the appended value by using multiple arguments. Time complexity: O(n)push_back
6 min read
std::replace and std::replace_if in C++
std::replace Assigns new_value to all the elements in the range [first, last) that compare to old_value. The function use operator == to compare the individual elements to old_value Function Template : void replace (ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value) first, last : Forward iterators to the in
4 min read
std::basic_string::at vs std::basic_string::operator[]
std::basic_string::at, std::basic_string::operator[]Both at() and operator[] can be used to access an element in the string. But there exists one difference between them on how to handle exceptional condition when pos>=size. std::basic_string::at throws std::out_of_range if pos >= size().std::bsic_string::operator[] throws no exception and pr
2 min read
std::find_if , std::find_if_not in C++
std :: find_if and std :: find_if_not are algorithm functions in C++ Standard Library in <algorithm> header file. These functions provide an efficient way to search for an element in a container using a predicate function. std :: find_if This function returns an iterator to the first element in the range [first, last) for which pred(Unary Fun
3 min read
std::next vs std::advance in C++
std::advance and std::next are used to advance the iterator by a certain position, such that we can make the iterator point to a desired position. Although both have same purpose, but their implementation is different from each other. This makes it important for us to understand the difference between the two. In C++11, std::next() will advance by
3 min read
std::rotate vs std::rotate_copy in C++ STL
rotate in STL:It rotates the order of the elements in the range [first, last), in such a way that the element pointed by middle becomes the new first element, i, e, to the left. // Illustrating the use of rotate algorithm #include <bits/stdc++.h> using namespace std; // Driver Program int main() { vector<int> arr; // set some values: 1
2 min read
std::stoul and std::stoull in C++
std::stoul Convert string to unsigned integer. Parses str interpreting its content as an integral number of the specified base, which is returned as an unsigned long value. unsigned long stoul (const string& str, size_t* idx = 0, int base = 10); Parameters : str : String object with the representation of an integral number. idx : Pointer to an
3 min read
std::vector::resize() vs. std::vector::reserve()
In C++, vectors are dynamically resizable arrays provided by STL. They can automatically change their size according to the number of elements and users also can change its size using the std::vector::resize()and std::vector::reserve(). But there is some difference in how these functions works. In this article, we will learn what are the difference
5 min read
std::stol() and std::stoll() Functions in C++
In C++, std::stol() and std::stoll() are the library functions used to convert the given string to integer value of type long int and long long int respectively. They are defined inside <string> header file. In this article, we will learn about std::stol() and std::stoll() functions in C++. Example: [GFGTABS] C++ // C++ program to illustrate
4 min read
std::upper_bound and std::lower_bound for Vector in C++ STL
The std::upper_bound() and std::lower_bound() functions are used for binary search operations STL containers that provide random access. They both are defined inside <algorithm> header file. In this article, we will learn how to use the std::upper_bound and std::lower_bound for vector in C++ STL. lower_bound() for VectorsThe std::lower_bound(
5 min read
Why we should avoid using std::endl
It is a common practice to use std::endl to print newlines while using cout. For small programs with very little I/O operations this practice is acceptable, but if the bulk of I/O operations increase, then the efficiency of the program is compromised. std::endl not only adds newlines to the stream, it also flushes the buffer each time it is used.Th
3 min read
std::to_wstring in c++
This function is used to convert the numerical value to the wide string i.e. it parses a numerical value of datatypes (int, long long, float, double ) to a wide string. It returns a wide string of data type wstring representing the numerical value passed in the function. In this function data type is being internally typecasted to the wstring data
3 min read
std::list::sort in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::sort() sort() function is used to sort the elements of the container by changing their positi
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg