C++ STL list, unique() code example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
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 the C++ unique() to remove adjacent duplicate elements or adjacent elements that satisfy some other binary predicate from the list in C++ programming
To show: How to use the C++ list, unique() to remove adjacent duplicate elements or adjacent elements that satisfy some other binary predicate from the list in C++ programming
// C++ STL list, unique()
#include <list>
#include <iostream>
using namespace std;
int main(void)
{
// container
list <int> ls1;
// iterators
list <int>::iterator ls1Iter, ls2Iter, ls3Iter;
not_equal_to<int> mypred;
// push/insert data
ls1.push_back(-12);
ls1.push_back(12);
ls1.push_back(12);
ls1.push_back(22);
ls1.push_back(22);
ls1.push_back(13);
ls1.push_back(-12);
ls1.push_back(14);
// print the data and do some operations
cout<<"ls1 data, the initial list: ";
for(ls1Iter = ls1.begin(); ls1Iter != ls1.end(); ls1Iter++)
cout<<" "<<*ls1Iter;
cout<<endl;
cout<<"\nOperation1: list <int> ls2 = ls1;"<<endl;
cout<<"Operation2: ls2.unique();"<<endl;
list <int> ls2 = ls1;
ls2.unique();
cout<<"ls2 data, after removing successive duplicate elements: ";
for(ls2Iter = ls2.begin(); ls2Iter != ls2.end(); ls2Iter++)
cout<<" "<<*ls2Iter;
cout<<endl;
cout<<"\nOperation1: list <int> ls3 = ls2;"<<endl;
cout<<"Operation2: ls3.unique(mypred);"<<endl;
list <int> ls3 = ls2;
ls3.unique(mypred);
cout<<"ls3 data, after removing successive unequal elements: ";
for(ls3Iter = ls3.begin(); ls3Iter != ls3.end(); ls3Iter++)
cout<<" "<<*ls3Iter;
cout<<endl;
return 0;
}
Output examples:
ls1 data, the initial list: -12 12 12 22 22 13 -12 14
Operation1: list <int> ls2 = ls1;
Operation2: ls2.unique();
ls2 data, after removing successive duplicate elements: -12 12 22 13 -12 14
Operation1: list <int> ls3 = ls2;
Operation2: ls3.unique(mypred);
ls3 data, after removing successive unequal elements: -12 -12
Press any key to continue . . .