This article is about the unique() algorithm function with std::array and std::vector
container. It is an STL algorithm in <algorithm> header file. It removes all the elements
except the first element from every consecutive group of equivalent elements in the range
[first, last). The function cannot alter the properties of the container which it is
performed on i.e. it cannot alter the size of the container after replacing the elements.
This is performed by removing the duplicate element by the first non-duplicate element.
The relative order of the elements not removed is preserved, while the elements between the
returned iterator and last are left in a valid but unspecified state.
unique() can take two forms:
(1) template <class ForwardIterator>
ForwardIterator unique (ForwardIterator first, ForwardIterator last);
(2) template <class ForwardIterator, class BinaryPredicate>
ForwardIterator unique (ForwardIterator first, ForwardIterator last,
Here the range used is [first, last). The first positioned element is included whereas the
last positioned element is not used. Elelments are compared and then swapped according to
the following rule:
two elements are compared equal using operator '==' in definition (1) or by using a
pred function in definition (2).
Return value: An iterator is returned which points to the last element that was not removed
in the range. All the elements between the first element and the iterator are considered as
Here the first definition is discussed.
Enter the name of employees along with their group number. Now display the total number of groups formed and
unique group ids of the employees.
#include<algorithm> // for unique function
#include<array> // for the array creation
#include<vector> // for the vector creation
using namespace std;
// structure of the employee object
const int num=10;
array <employee, num> emp;
cout<<"Enter the Employee Details: \n";
for(i = 0; i < num; i++)
cout<<"Group Number: ";
// storing the groups of the employees in a different vector
vector <int> grp;
// sorting the elements of the vector so that the consecutive elements could be removed
auto it = unique(grp.begin(),grp.end());
// displaying unique groups
cout<<"Total unique groups are: "<<distance(grp.begin(),it)<<endl;
cout<<"The group IDs are: ";