copy() algorithm是很好用的algorithm,但偏偏就是沒有copy_if(),但透過remove_copy_if()則可達到相同的要求。
remove_copy_if()的思考方式和copy_if()相反,若UnaryPredicate為true,則不copy,若為false,則copy。
此範例demo若為remove_copy_if() algorithm,先輸出奇數,再輸出偶數。
1
/**/
/*
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : GenericAlgo_remove_copy_if.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use remove_copy_if() algorithm
7Release : 11/12/2006 1.0
8*/
9
10 #include < iostream >
11 #include < algorithm >
12 #include < vector >
13
14 using namespace std;
15
16 bool isOdd( int );
17 bool isEven( int );
18
19 int main() {
20 vector<int> ivec;
21 copy(istream_iterator<int>(cin), istream_iterator<int>(), back_inserter(ivec));
22
23 remove_copy_if(ivec.begin(), ivec.end(), ostream_iterator<int>(cout, " "), isEven);
24 cout << endl;
25 remove_copy_if(ivec.begin(), ivec.end(), ostream_iterator<int>(cout," "), isOdd);
26
27 return 0;
28}
29
30 bool isOdd( int val) {
31 return val%2;
32}
33
34 bool isEven( int val) {
35 return !(val%2);
36}
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : GenericAlgo_remove_copy_if.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use remove_copy_if() algorithm
7Release : 11/12/2006 1.0
8*/
9
10 #include < iostream >
11 #include < algorithm >
12 #include < vector >
13
14 using namespace std;
15
16 bool isOdd( int );
17 bool isEven( int );
18
19 int main() {
20 vector<int> ivec;
21 copy(istream_iterator<int>(cin), istream_iterator<int>(), back_inserter(ivec));
22
23 remove_copy_if(ivec.begin(), ivec.end(), ostream_iterator<int>(cout, " "), isEven);
24 cout << endl;
25 remove_copy_if(ivec.begin(), ivec.end(), ostream_iterator<int>(cout," "), isOdd);
26
27 return 0;
28}
29
30 bool isOdd( int val) {
31 return val%2;
32}
33
34 bool isEven( int val) {
35 return !(val%2);
36}
執行結果
1
1
2
3
4
5
6
2 ^Z
3 1 3 5
4 2 4 6 請按任意鍵繼續 . . .
2 ^Z
3 1 3 5
4 2 4 6 請按任意鍵繼續 . . .