Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-04-09 07:49:13

0001 // name=std__unique_copy ; gcc $name.cc -std=c++11 -lstdc++ -o /tmp/$name && /tmp/$name
0002 
0003 /**
0004 https://stackoverflow.com/questions/28100712/better-way-of-counting-unique-item
0005 
0006 https://cplusplus.com/reference/algorithm/unique_copy/
0007 **/
0008 
0009 
0010 // unique_copy example
0011 #include <iostream>     // std::cout
0012 #include <algorithm>    // std::unique_copy, std::sort, std::distance
0013 #include <vector>       // std::vector
0014 
0015 bool myfunction (int i, int j) {
0016   return (i==j);
0017 }
0018 
0019 int main () {
0020   int myints[] = {10,20,20,20,30,30,20,20,10};
0021   std::vector<int> myvector (9);                            // 0  0  0  0  0  0  0  0  0
0022 
0023   // using default comparison:
0024   std::vector<int>::iterator it;
0025   it=std::unique_copy (myints,myints+9,myvector.begin());   // 10 20 30 20 10 0  0  0  0
0026                                                             //                ^
0027 
0028   std::sort (myvector.begin(),it);                          // 10 10 20 20 30 0  0  0  0
0029                                                             //                ^
0030 
0031   // using predicate comparison:
0032   it=std::unique_copy (myvector.begin(), it, myvector.begin(), myfunction);
0033                                                             // 10 20 30 20 30 0  0  0  0
0034                                                             //          ^
0035 
0036   myvector.resize( std::distance(myvector.begin(),it) );    // 10 20 30
0037 
0038   // print out content:
0039   std::cout << "myvector contains:";
0040   for (it=myvector.begin(); it!=myvector.end(); ++it)
0041     std::cout << ' ' << *it;
0042   std::cout << '\n';
0043 
0044   return 0;
0045 }
0046 
0047 
0048