1、remove_if
- /*
- *remove if example
- */
- #include <iostream>
- #include <algorithm>
- #include <vector>
- using namespace std;
- bool isOdd(int i)
- {
- return ((i%2)==1);
- }
- int main(int argc,char **argv)
- {
- int myints[] = {1,2,3,4,5,6,7,8,9}; //1 2 3 4 5 6 7 8 9
- //bounds of range
- int *pbegin = myints;
- int *pend = myints + sizeof(myints)/sizeof(int);
- pend = remove_if(pbegin,pend,isOdd); // 2 4 6 8
- for(int *p=pbegin;p!=pend;++p)
- cout << “ ” << *p ;
- cout << endl;
- return 0;
- }
2、sort:
- /*
- *unique example
- */
- #include <iostream>
- #include <algorithm>
- #include <vector>
- using namespace std;
- bool myfunction(int i,int j)
- {
- return (i<j);
- }
- struct myclass{
- bool operator()(int i,int j)
- {
- return (i<j);
- }
- }myobject;
- //print vector contains
- void print(vector <int> v)
- {
- vector<int>::iterator it;
- cout << “myvector contains: ”;
- for(it=v.begin();it!=v.end();it++)
- cout << *it << “ ”;
- cout << endl;
- }
- int main(int argc,char **argv)
- {
- int myints[] = {32,87,12,45,25,70,53,9};
- vector<int> myvector(myints,myints+8);
- vector<int>::iterator it;
- print(myvector); //32 87 12 45 25 70 53 9
- //using default comparison(operator <)
- sort(myvector.begin(),myvector.begin()+4);
- print(myvector); //12 32 45 87 25 70 53 9
- //using function as comparison
- sort(myvector.begin()+4,myvector.end(),myfunction);
- print(myvector); //12 32 45 87 9 25 53 70
- //using object as comparison
- sort(myvector.begin(),myvector.end(),myobject);
- print(myvector); //9 12 25 32 45 53 70 87
- return 0;
- }
3、unique
- /*
- *unique algorithm example
- */
- #include <iostream>
- #include <algorithm>
- #include <vector>
- using namespace std;
- bool myfunction(int i,int j)
- {
- return (i==j);
- }
- //print vector contains
- void print(vector <int> v)
- {
- vector<int>::iterator it;
- cout << “myvector contains: ”;
- for(it=v.begin();it!=v.end();it++)
- cout << *it << “ ”;
- cout << endl;
- }
- int main(int argc,char **argv)
- {
- int myints[] = {10,20,20,20,30,30,20,20,10}; // 10 20 20 20 30 30 20 20 10
- vector<int> myvector (myints,myints+9);
- vector<int>::iterator it;
- print(myvector);
- cout << myvector.size() << endl; //9
- // using default comparison:
- it = unique (myvector.begin(), myvector.end()); // 10 20 30 20 10 ? ? ? ?
- cout << myvector.size() << endl; //9
- myvector.resize( it - myvector.begin() ); // 10 20 30 20 10
- // using predicate comparison:
- unique (myvector.begin(), myvector.end(), myfunction); // (no changes)
- print(myvector);
- cout << myvector.size() << endl; //5
- return 0;
- }
C++ Vector容器中remove_if、sort、unique的简单用法