(原創) 如何使用for_each() algorithm? (C/C++) (STL)

來源:互聯網
上載者:User

很懷念VB和C#的foreach文法嗎?對於C++只能用for文法造成程式冗長覺得很煩嗎?foreach的確對於container而言非常好用且精簡,C++/CLI已經增加上了for each文法了,事實上,C++也可使用foreach喔,STL提供了for_each() algorithm,可以彌補這個缺憾。

for_each() algorithm會將每個iterator當作const iterator處理,若只用普通的function,直接將function name傳入即可,別忘了function name本身也是個pointer,若要用template function,則必須將該template function轉成function pointer才可傳進for_each algorithm,以下範例demo for_each() algorithm的用法。

 1/**//* 
 2(C) OOMusou 2006 http://oomusou.cnblogs.com
 3
 4Filename    : GenericAlgo_for_each.cpp
 5Compiler    : Visual C++ 8.0
 6Description : Demo how to use for_each algorithm.
 7              Applies a specified function object to each element 
 8              in a forward order within a range and returns the 
 9              function object.
10Release     : 11/19/2006
11*/
12
13#include <iostream>
14#include <vector>
15#include <algorithm>
16
17template <class T>
18void coutIterator1(T &);
19
20void coutIterator2(int &);
21
22int main() {
23  std::vector<int> ivec(3,1);
24
25  void (*pf) (int &) = coutIterator1;
26  for_each(ivec.begin(), ivec.end(), pf);
27
28  std::cout << std::endl;
29
30  for_each(ivec.begin(), ivec.end(), coutIterator2);
31
32  return 0;
33}
34
35template <class T>
36void coutIterator1(T &iter) {
37  std::cout << iter << std::endl;
38}
39
40void coutIterator2(int &i) {
41  std::cout << i << std::endl;
42}

for_each() algorithm不能修改iterator,若要修改iterator,需用transform() algorithm。

See Also
(原創) 如何正確的使用迴圈(使用for_each)? (C/C++) (STL) (template)

Reference
C++ Primer 3rd中文版 P.1145

相關文章

聯繫我們

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