1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
// list::unique
#include <iostream>
#include <cmath>
#include <list>
// a binary predicate implemented as a function:
bool same_integral_part(double first, double second)
{
return (int(first) == int(second));
}
// a binary predicate implemented as a class:
struct is_near {
bool operator() (double first, double second)
{
return (fabs(first - second)<5.0);
}
};
int main()
{
int myindex[] = { 1, 0, 0, 1, 2,
0, 1, 3, 5, 4 };
std::list<int> mylist(myindex, myindex + 10);
//double mydoubles[] = { 12.15, 2.72, 73.0, 12.77, 3.14,
// 12.77, 73.35, 72.25, 15.3, 72.25 };
//std::list<double> mylist(mydoubles, mydoubles + 10);
mylist.sort(); // 2.72, 3.14, 12.15, 12.77, 12.77,
// 15.3, 72.25, 72.25, 73.0, 73.35
mylist.unique(); // 2.72, 3.14, 12.15, 12.77
// 15.3, 72.25, 73.0, 73.35
int counter=0;
for (std::list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it) {
std::cout << ' ' << *it;
myindex[counter]=*it;
++counter;
}
std::cout << std::endl;
for (int i = 0; i < counter; ++i) {
std::cout << ' ' << myindex[i];
}
std::cout << '\n';
mylist.unique(same_integral_part); // 2.72, 3.14, 12.15
// 15.3, 72.25, 73.0
mylist.unique(is_near()); // 2.72, 12.15, 72.25
std::cout << "mylist contains:";
for (std::list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
system("pause");
return 0;
}
| |