C++ std::unique_copy with std::vector














































C++ std::unique_copy with std::vector



 This article is about the unique_copy() algorithm function with std::array and std::vector
 container. It is an STL algorithm in <algorithm> header file.
 It copies all the first element from every consecutive group of equivalent elements in the
 range [first, last).
 
unique_copy() can take two forms:
(1) template <class InputIterator, class OutputIterator>
OutputIterator unique_copy (InputIterator first, InputIterator last,
OutputIterator result);
(2) template <class InputIterator, class OutputIterator, class BinaryPredicate>
OutputIterator unique_copy (InputIterator first, InputIterator last,
OutputIterator result, 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 of the copied range.

Here the second definition is discussed.

 Program:
 Enter the employee details and then store and display the unique groups of the employees.

#include<iostream>
#include<algorithm> // for unique function
#include<vector> // for the vector creation

using namespace std;
// structure of the employee object
struct employee
{
char name[30];
int group;
};
// function for checking the equality og the groups
bool eq(employee a, employee b)
{
return (a.group==b.group);
}

int main()
{
int num;
int i;
cout<<"Enter the number of employees: ";
cin>>num;

vector <employee> emp, emp1(num);

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

auto it = unique_copy(emp.begin(),emp.end(),emp1.begin(),eq);

// displaying unique consecutive group
emp1.resize(distance(emp1.begin(),it));
cout<<"The group IDs are: ";
for(auto j=emp1.begin();j!=emp1.end();j++)
cout<<j->group<<" ";
}

Comments