如何列出陣列中大於n的所有元素? (C/C++) (STL)

來源:互聯網
上載者:User

Abstract
若用C語言配合迴圈,這是個很簡單的題目,但若用C++配合STL,則有很漂亮的寫法。

Introduction
陣列中有2、3、1、3、5五個值,希望能列出大於2的所有元素。

C++

1 /* 
2 (C) OOMusou 2008 http://oomusou.cnblogs.com

4 Filename    : GenericAlgo_remove_copy_if_predicate.cpp
5 Compiler    : Visual C++ 8.0
6 Description : Demo how to use remove_copy_if() & predicate
7 Release     : 01/29/2008 1.0
8 */

10 #include <iostream>
11 #include <algorithm>
12 #include <functional>
13 
14 using namespace std;
15 
16 int main() {
17   int ia[] = {2, 3, 1 ,3 ,5};
18   int arr_size = sizeof(ia) / sizeof(int);
19  
20   remove_copy_if(ia, ia + arr_size, ostream_iterator<int>(cout, " "), bind2nd(less_equal<int>(), 2));
21 }

執行結果

3 3 5

20行

remove_copy_if(ia, ia + arr_size, ostream_iterator<int>(cout, " "), bind2nd(less_equal<int>(), 2));

我們知道copy()可將陣列內的元素透過ostream_interator顯示,而目前只想列出大於2的元素,直覺會想找copy_if(),但STL並沒有提供copy_if(),只提供了remove_copy_if(),所以得反向思考,所謂的『大於2』相當於剔除所有『小於等於2』的元素,所以我們必須使用less_equal<int>()這個binary predicate,由於現在是『小於等於2』,所以還需要bind2nd()將2 bind給less_equal<int>()。

Conclusion
這種functional programming的寫法,和傳統的寫法不太一樣,需要一段時間適應,C#之父Anders Hejisberg也認為functional programming將越來越重要,所以C# 3也開始支援lambda,而STL和boost更早已將這種functional programming發揮的淋漓盡致。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.