现代C++中强调,使用基于范围的 for 循环(Visual studio 2012之后的),相比于旧版的 for 循环更整洁和易于使用,并且不容易发生意外错误。让我们一睹为快。

当然,使用前需要包含头文件:

  1. #include <algorithm>

1 基于范围的for语句

基于范围的for语句(Range-based for Statement),其语句形式为:

  1. for ( for-range-declaration : expression )
  2. statement

看一段示例代码:

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. int main()
  5. {
  6. cout << "Test 1 : ";
  7. // Basic 10-element integer array.
  8. int x[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  9. // Range-based for loop to iterate through the array.
  10. for( int y : x ) { // Access by value using a copy declared as a specific type.
  11. // Not preferred.
  12. cout << y << " ";
  13. }
  14. cout << endl;
  15. cout << "Test 2 : ";
  16. // The auto keyword causes type inference to be used. Preferred.
  17. for( auto y : x ) { // Copy of 'x', almost always undesirable
  18. cout << y << " ";
  19. }
  20. cout << endl;
  21. cout << "Test 3 : ";
  22. for( auto &y : x ) { // Type inference by reference.
  23. // Observes and/or modifies in-place. Preferred when modify is needed.
  24. cout << y << " ";
  25. }
  26. cout << endl;
  27. cout << "Test 4 : ";
  28. for( const auto &y : x ) { // Type inference by reference.
  29. // Observes in-place. Preferred when no modify is needed.
  30. cout << y << " ";
  31. }
  32. cout << endl;
  33. cout << "Test 5 : ";
  34. // Create a vector object that contains 10 elements.
  35. vector<double> v;
  36. for (int i = 0; i < 10; ++i) {
  37. v.push_back(i + 0.14159);
  38. }
  39. // Range-based for loop to iterate through the vector, observing in-place.
  40. for( const auto &j : v ) {
  41. cout << j << " ";
  42. }
  43. cout << endl;
  44. }

输出结果为:

  1. Test 1 : 1 2 3 4 5 6 7 8 9 10
  2. Test 2 : 1 2 3 4 5 6 7 8 9 10
  3. Test 3 : 1 2 3 4 5 6 7 8 9 10
  4. Test 4 : 1 2 3 4 5 6 7 8 9 10
  5. Test 5 : 0.14159 1.14159 2.14159 3.14159 4.14159 5.14159 6.14159 7.14159 8.14159 9.14159

2 for_each语句

for_each语句,其语句形式为:

  1. template<class InputIterator, class Function>
  2. Function for_each(
  3. InputIterator _First,
  4. InputIterator _Last,
  5. Function _Func
  6. );

其中,_First是迭代器对应起始元素位置,_Last是迭代器对应的结束位置,必须是序列中可以访问的位置,_Func是用户定义的函数对象,将在迭代器范围内的所有元素,均应用到该函数中。

看一段代码示例:

  1. // alg_for_each.h
  2. #include <vector>
  3. #include <algorithm>
  4. #include <iostream>
  5. // The function object multiplies an element by a Factor
  6. template <class Type>
  7. class MultValue
  8. {
  9. private:
  10. Type Factor; // The value to multiply by
  11. public:
  12. // Constructor initializes the value to multiply by
  13. MultValue ( const Type& _Val ) : Factor ( _Val ) {
  14. }
  15. // The function call for the element to be multiplied
  16. void operator ( ) ( Type& elem ) const
  17. {
  18. elem *= Factor;
  19. }
  20. };
  21. // The function object to determine the average
  22. class Average
  23. {
  24. private:
  25. long num; // The number of elements
  26. long sum; // The sum of the elements
  27. public:
  28. // Constructor initializes the value to multiply by
  29. Average ( ) : num ( 0 ) , sum ( 0 )
  30. {
  31. }
  32. // The function call to process the next elment
  33. void operator ( ) ( int elem ) \
  34. {
  35. num++; // Increment the element count
  36. sum += elem; // Add the value to the partial sum
  37. }
  38. // return Average
  39. operator double ( )
  40. {
  41. return static_cast <double> (sum) /
  42. static_cast <double> (num);
  43. }
  44. };
  1. // main.cpp
  2. #include "alg_for_each.h"
  3. void main( )
  4. {
  5. vector <int> v1;
  6. vector <int>::iterator Iter1;
  7. // Constructing vector v1
  8. int i;
  9. for ( i = -4 ; i <= 2 ; i++ )
  10. {
  11. v1.push_back( i );
  12. }
  13. cout << "Original vector v1 = ( " ;
  14. for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
  15. cout << *Iter1 << " ";
  16. cout << ")." << endl;
  17. // Using for_each to multiply each element by a Factor
  18. for_each ( v1.begin ( ) , v1.end ( ) , MultValue<int> ( -2 ) );
  19. cout << "Multiplying the elements of the vector v1\n "
  20. << "by the factor -2 gives:\n v1mod1 = ( " ;
  21. for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
  22. cout << *Iter1 << " ";
  23. cout << ")." << endl;
  24. // The function object is templatized and so can be
  25. // used again on the elements with a different Factor
  26. for_each (v1.begin ( ) , v1.end ( ) , MultValue<int> (5 ) );
  27. cout << "Multiplying the elements of the vector v1mod\n "
  28. << "by the factor 5 gives:\n v1mod2 = ( " ;
  29. for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
  30. cout << *Iter1 << " ";
  31. cout << ")." << endl;
  32. // The local state of a function object can accumulate
  33. // information about a sequence of actions that the
  34. // return value can make available, here the Average
  35. double avemod2 = for_each ( v1.begin ( ) , v1.end ( ) ,
  36. Average ( ) );
  37. cout << "The average of the elements of v1 is:\n Average ( v1mod2 ) = "
  38. << avemod2 << "." << endl;
  39. }

运行结果为:

  1. Original vector v1 = ( -4 -3 -2 -1 0 1 2 ).
  2. Multiplying the elements of the vector v1
  3. by the factor -2 gives:
  4. v1mod1 = ( 8 6 4 2 0 -2 -4 ).
  5. Multiplying the elements of the vector v1mod
  6. by the factor 5 gives:
  7. v1mod2 = ( 40 30 20 10 0 -10 -20 ).
  8. The average of the elements of v1 is:
  9. Average ( v1mod2 ) = 10.

现代C++ 基于范围的for和for_each语句的更多相关文章

  1. 基于游标的定位DELETE/UPDATE语句

    如果游标是可更新的(也就是说,在定义游标语句中不包括Read Only 参数),就可以用游标从游标数据的源表中DELETE/UPDATE行,即DELETE/UPDATE基于游标指针的当前位置的操作: ...

  2. 17.1.2.1 Advantages and Disadvantages of Statement-Based and Row-Based Replication 基于语句和行的复制的优势和劣势

    17.1.2.1 Advantages and Disadvantages of Statement-Based and Row-Based Replication 基于语句和行的复制的优势和劣势 每 ...

  3. 基于简单sql语句的sql解析原理及在大数据中的应用

    基于简单sql语句的sql解析原理及在大数据中的应用 李万鸿 老百姓呼吁打土豪分田地.共同富裕,总有一天会实现. 全面了解你所不知道的外星人和宇宙真想:http://pan.baidu.com/s/1 ...

  4. 现代C++

    C++ 是世界上最常用的编程语言之一. 编写良好的 C++ 程序是快速.高效的. 该语言比其他语言更加灵活,因为你可以使用它来创建各种应用,包括有趣刺激的游戏.高性能科学软件.设备驱动程序.嵌入式程序 ...

  5. C++ primer plus读书笔记——第16章 string类和标准模板库

    第16章 string类和标准模板库 1. string容易被忽略的构造函数: string(size_type n, char c)长度为n,每个字母都为c string(const string ...

  6. [MySQL Reference Manual] 8 优化

    8.优化 8.优化 8.1 优化概述 8.2 优化SQL语句 8.2.1 优化SELECT语句 8.2.1.1 SELECT语句的速度 8.2.1.2 WHERE子句优化 8.2.1.3 Range优 ...

  7. 数据处理之CoreData

    一.CoreData数据库框架与Sqlite对比 Sqlite: 1.基于C接口, 需要使用sql语句, 代码繁琐 2.在处理大量数据时, 表关系更直观 3.在OC中不是可视化的 CoreData: ...

  8. 在SQL Server 2014里可更新的列存储索引 (Updateable Column Store Indexes)

    传统的关系数据库服务引擎往往并不是对超大量数据进行分析计算的最佳平台,为此,SQL Server中开发了分析服务引擎去对大笔数据进行分析计算.当然,对于数据的存放平台SQL Server数据库引擎而言 ...

  9. 为什么我会选IT【这几年是怎么过来的】

    导火线 晚上跟高中同学说我近来的状况,无意中他提到:“如果当初没意外话,今年估计你就是一名老师了吧”.这让我很是怀念以前的日子,这四年来过的很快,开始想着当初是怎么过来的 : 高考 本人英语不佳,高考 ...

随机推荐

  1. 使用 Jersey 和 Apache Tomcat 构建 RESTful Web 服务

    作者: Yi Ming Huang, 软件工程师, IBM Dong Fei Wu, 软件工程师, IBM Qing Guo, 软件工程师, IBM 出处: http://www.ibm.com/de ...

  2. php 密码hash加密

    做密码加密,记录一下. password_hash 函数在 PHP 5.5 时被引入. 此函数现在使用的是目前 PHP 所支持的最强大的加密算法 BCrypt .例子: $passwordHash = ...

  3. C++函数传递数组的两种方式

    数组与指针. 传首地址过去,然后通过地址输出数组元素. 1.一维数组 #include<iostream> using namespace std; #include <cstrin ...

  4. Memcached的实战笔记

    官网:http://memcached.org/ 优秀Blogs: http://blog.csdn.net/jingqiang521/article/details/48345021 开启telne ...

  5. js-DOM操作基本知识

  6. Nginx 实现反向代理

    Nginx 实现反向代理 两个域名指向同一台 Nginx 服务器,用户访问不同的域名显示不同的网页内容 两个域名分别是 www.test1.com www.test2.com 1.准备工作 下载及安装 ...

  7. Mysql怎么样避免全表扫描,sql查询优化

    对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引: 尝试下面的技巧以避免优化器错选了表扫描: 使用ANALYZE TABLE tbl_name为扫 ...

  8. 从100PV到1亿级PV站点架构演变

    假设你对项目管理.系统架构有兴趣,请加微信订阅号"softjg".增加这个PM.架构师的大家庭 一个站点就像一个人,存在一个从小到大的过程. 养一个站点和养一个人一样.不同一时候期 ...

  9. intellij idea 13&amp;14 插件推荐及高速上手建议 (已更新!)

    早些年 在外企的时候,公司用的是intellij idea ,当时也是从eclipse.MyEclipse转过去的非常是不习惯. 用了一周明显感觉爱上它了.由于它非常智能,并且能纠正你非常多不好的习惯 ...

  10. 【甘道夫】Hadoop2.2.0环境使用Sqoop-1.4.4将Oracle11g数据导入HBase0.96,并自己主动生成组合行键

    目的: 使用Sqoop将Oracle中的数据导入到HBase中,并自己主动生成组合行键! 环境: Hadoop2.2.0 Hbase0.96 sqoop-1.4.4.bin__hadoop-2.0.4 ...