C++ STL algorithm unique_copy() program example

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using unique_copy() to copy elements from a source range into a destination range except for the duplicate elements that are adjacent to each other in C++ programming

To show: How to use the C++ algorithm, unique_copy() to copy elements from a source range into a destination range except for the duplicate elements that are adjacent to each other in C++ programming

// C++ STL algorithm unique_copy()

#include <vector>

#include <algorithm>

#include <functional>

#include <iostream>

using namespace std;

// return whether modulus of elem1 is equal to modulus of elem2

bool mod_equal(int elem1, int elem2)

{

if(elem1 < 0)

elem1 = - elem1;

if(elem2 < 0)

elem2 = - elem2;

return (elem1 == elem2);

};

int main()

{

// vector container

vector <int> vec1;

// vector iterators

vector <int>::iterator vec1_Iter1, vec1_Iter2, vec1_NewEnd1, vec1_NewEnd2;

int i, j, k;

// push the range

for(i = 0; i <= 1; i++)

{

vec1.push_back(8);

vec1.push_back(-8);

}

// push data in the range

for(j = 0; j <= 2; j++)

vec1.push_back(5);

// push data individually

vec1.push_back(9);

vec1.push_back(9);

// push data in the range

for(k = 0; k <= 5; k++)

vec1.push_back(12);

// print the data

cout<<"vec1 vector data is: ";

for(vec1_Iter1 = vec1.begin(); vec1_Iter1 != vec1.end(); vec1_Iter1++)

cout<<*vec1_Iter1<<" ";

cout<<endl;

// copy first half to second, removing consecutive duplicates

vec1_NewEnd1 = unique_copy(vec1.begin(), vec1.begin() + 8, vec1.begin() + 8);

cout<<"\nCopying the first half of the vector to the second half\nwhile removing adjacent duplicates gives: ";

for(vec1_Iter1 = vec1.begin(); vec1_Iter1 != vec1_NewEnd1; vec1_Iter1++)

cout<<*vec1_Iter1<<" ";

cout<<endl;

for(int l = 0; l <= 7; l++)

vec1.push_back(10);

// remove consecutive duplicates under the binary predicate mod_equals

vec1_NewEnd2 = unique_copy(vec1.begin(), vec1.begin() + 14, vec1.begin() + 14, mod_equal);

cout<<"\nCopying the first half of the vector to the second half\n"

<<"removing adjacent duplicates under mod_equal() gives: ";

for(vec1_Iter2 = vec1.begin(); vec1_Iter2 != vec1_NewEnd2; vec1_Iter2++)

cout<<*vec1_Iter2<<" ";

cout<<endl;

}

Output examples:

vec1 vector data is: 8 -8 8 -8 5 5 5 9 9 12 12 12 12 12 12

Copying the first half of the vector to the second half

while removing adjacent duplicates gives: 8 -8 8 -8 5 5 5 9 8 -8 8 -8 5 9

Copying the first half of the vector to the second half

removing adjacent duplicates under mod_equal() gives: 8 -8 8 -8 5 5 5 9 8 -8 8 -8 5 9 8 5 9 8 5 9

Press any key to continue . . .