C++ std::unique with std::array and std::vector














































C++ std::unique with std::array and std::vector



 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,
                        BinaryPredicate pred);
 
 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
 non-duplicate.

 Here the first definition is discussed.
 
 Program:
 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<iostream>    
#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
struct employee
{
char name[30];
int group;
};

int main()
{
const int num=10;
int i;

array <employee, num> emp;

cout<<"Enter the Employee Details: \n";
for(i = 0; i < num; i++)
{
cout<<"Name: ";
cin>>emp[i].name;
cout<<"Group Number: ";
cin>>emp[i].group;
}

// storing the groups of the employees in a different vector
vector <int> grp;
for(i=0;i<num;i++)
grp.push_back(emp[i].group);

// sorting the elements of the vector so that the consecutive elements could be removed
sort(grp.begin(),grp.end());

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: ";
for(auto i=grp.begin();i!=it;i++)
cout<<*i<<" ";
    } 

Comments