如何使用remove_copy_if() algorithm? (C/C++) (STL)

來源:互聯網
上載者:User

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
14using namespace std;
15
16bool isOdd(int);
17bool isEven(int);
18
19int 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
30bool isOdd(int val) {
31  return val%2;
32}
33
34bool isEven(int val) {
35  return !(val%2);
36}

執行結果

11 2 3 4 5 6
2^Z
31 3 5
42 4 6 請按任意鍵繼續 . . .
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.