C++ STL algorithm unique() 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 remove the duplicate elements that are adjacent to each other in a specified range in C++ programming

To show: How to use the C++ algorithm, unique() to remove the duplicate elements that are adjacent to each other in a specified range in C++ programming

// C++ STL, algorithm unique()

#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(void)

{

// vector container

vector <int> vec1;

// vector iterator

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

int i, j;

// push the data in range

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

{

vec1.push_back(4);

vec1.push_back(7);

vec1.push_back(-4);

}

// push the data in range

for(j = 1; j <= 4; j++)

vec1.push_back(8);

// push the data individually

vec1.push_back(9);

vec1.push_back(9);

cout<<"vec1 vector data: ";

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

cout<<*vec1_Iter1<<" ";

cout<<endl;

// remove consecutive duplicates

vec1_NewEnd1 = unique(vec1.begin(), vec1.end());

cout<<"\nRemoving adjacent duplicates from vec1 vector gives: ";

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

cout<<*vec1_Iter1<<" ";

cout<<endl;

// remove consecutive duplicates under the binary predicate mod_equal()

vec1_NewEnd2 = unique(vec1.begin(), vec1_NewEnd1, mod_equal);

cout<<"\nRemoving adjacent duplicates from vec1 vector under\nthe "

<<"binary predicate mod_equal() gives: ";

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

cout<<*vec1_Iter2<<" ";

cout<<endl;

// remove elements if preceded by an element that was greater

vec1_NewEnd3 = unique(vec1.begin(), vec1_NewEnd2, greater<int>());

cout<<"\nRemoving adjacent elements satisfying the binary\n"

<<"predicate mod_equal() from vec1 vector gives: ";

for(vec1_Iter3 = vec1.begin(); vec1_Iter3 != vec1_NewEnd3; vec1_Iter3++)

cout<<*vec1_Iter3<<" ";

cout<<endl;

return 0;

}

Output examples:

vec1 vector data: 4 7 -4 4 7 -4 4 7 -4 4 7 -4 8 8 8 8 9 9

Removing adjacent duplicates from vec1 vector gives: 4 7 -4 4 7 -4 4 7 -4 4 7 -4 8 9

Removing adjacent duplicates from vec1 vector under

the binary predicate mod_equal() gives: 4 7 -4 7 -4 7 -4 7 -4 8 9

Removing adjacent elements satisfying the binary

predicate mod_equal() from vec1 vector gives: 4 7 7 7 7 8 9

Press any key to continue . . .