现代C++ 基于范围的for和for_each语句
现代C++中强调,使用基于范围的 for 循环(Visual studio 2012之后的),相比于旧版的 for 循环更整洁和易于使用,并且不容易发生意外错误。让我们一睹为快。
当然,使用前需要包含头文件:
#include <algorithm>
1 基于范围的for语句
基于范围的for语句(Range-based for Statement),其语句形式为:
for ( for-range-declaration : expression )statement
看一段示例代码:
#include <iostream>#include <vector>using namespace std;int main(){cout << "Test 1 : ";// Basic 10-element integer array.int x[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };// Range-based for loop to iterate through the array.for( int y : x ) { // Access by value using a copy declared as a specific type.// Not preferred.cout << y << " ";}cout << endl;cout << "Test 2 : ";// The auto keyword causes type inference to be used. Preferred.for( auto y : x ) { // Copy of 'x', almost always undesirablecout << y << " ";}cout << endl;cout << "Test 3 : ";for( auto &y : x ) { // Type inference by reference.// Observes and/or modifies in-place. Preferred when modify is needed.cout << y << " ";}cout << endl;cout << "Test 4 : ";for( const auto &y : x ) { // Type inference by reference.// Observes in-place. Preferred when no modify is needed.cout << y << " ";}cout << endl;cout << "Test 5 : ";// Create a vector object that contains 10 elements.vector<double> v;for (int i = 0; i < 10; ++i) {v.push_back(i + 0.14159);}// Range-based for loop to iterate through the vector, observing in-place.for( const auto &j : v ) {cout << j << " ";}cout << endl;}
输出结果为:
Test 1 : 1 2 3 4 5 6 7 8 9 10Test 2 : 1 2 3 4 5 6 7 8 9 10Test 3 : 1 2 3 4 5 6 7 8 9 10Test 4 : 1 2 3 4 5 6 7 8 9 10Test 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语句,其语句形式为:
template<class InputIterator, class Function>Function for_each(InputIterator _First,InputIterator _Last,Function _Func);
其中,_First是迭代器对应起始元素位置,_Last是迭代器对应的结束位置,必须是序列中可以访问的位置,_Func是用户定义的函数对象,将在迭代器范围内的所有元素,均应用到该函数中。
看一段代码示例:
// alg_for_each.h#include <vector>#include <algorithm>#include <iostream>// The function object multiplies an element by a Factortemplate <class Type>class MultValue{private:Type Factor; // The value to multiply bypublic:// Constructor initializes the value to multiply byMultValue ( const Type& _Val ) : Factor ( _Val ) {}// The function call for the element to be multipliedvoid operator ( ) ( Type& elem ) const{elem *= Factor;}};// The function object to determine the averageclass Average{private:long num; // The number of elementslong sum; // The sum of the elementspublic:// Constructor initializes the value to multiply byAverage ( ) : num ( 0 ) , sum ( 0 ){}// The function call to process the next elmentvoid operator ( ) ( int elem ) \{num++; // Increment the element countsum += elem; // Add the value to the partial sum}// return Averageoperator double ( ){return static_cast <double> (sum) /static_cast <double> (num);}};
// main.cpp#include "alg_for_each.h"void main( ){vector <int> v1;vector <int>::iterator Iter1;// Constructing vector v1int i;for ( i = -4 ; i <= 2 ; i++ ){v1.push_back( i );}cout << "Original vector v1 = ( " ;for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )cout << *Iter1 << " ";cout << ")." << endl;// Using for_each to multiply each element by a Factorfor_each ( v1.begin ( ) , v1.end ( ) , MultValue<int> ( -2 ) );cout << "Multiplying the elements of the vector v1\n "<< "by the factor -2 gives:\n v1mod1 = ( " ;for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )cout << *Iter1 << " ";cout << ")." << endl;// The function object is templatized and so can be// used again on the elements with a different Factorfor_each (v1.begin ( ) , v1.end ( ) , MultValue<int> (5 ) );cout << "Multiplying the elements of the vector v1mod\n "<< "by the factor 5 gives:\n v1mod2 = ( " ;for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )cout << *Iter1 << " ";cout << ")." << endl;// The local state of a function object can accumulate// information about a sequence of actions that the// return value can make available, here the Averagedouble avemod2 = for_each ( v1.begin ( ) , v1.end ( ) ,Average ( ) );cout << "The average of the elements of v1 is:\n Average ( v1mod2 ) = "<< avemod2 << "." << endl;}
运行结果为:
Original vector v1 = ( -4 -3 -2 -1 0 1 2 ).Multiplying the elements of the vector v1by the factor -2 gives:v1mod1 = ( 8 6 4 2 0 -2 -4 ).Multiplying the elements of the vector v1modby the factor 5 gives:v1mod2 = ( 40 30 20 10 0 -10 -20 ).The average of the elements of v1 is:Average ( v1mod2 ) = 10.
现代C++ 基于范围的for和for_each语句的更多相关文章
- 基于游标的定位DELETE/UPDATE语句
		
如果游标是可更新的(也就是说,在定义游标语句中不包括Read Only 参数),就可以用游标从游标数据的源表中DELETE/UPDATE行,即DELETE/UPDATE基于游标指针的当前位置的操作: ...
 - 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 基于语句和行的复制的优势和劣势 每 ...
 - 基于简单sql语句的sql解析原理及在大数据中的应用
		
基于简单sql语句的sql解析原理及在大数据中的应用 李万鸿 老百姓呼吁打土豪分田地.共同富裕,总有一天会实现. 全面了解你所不知道的外星人和宇宙真想:http://pan.baidu.com/s/1 ...
 - 现代C++
		
C++ 是世界上最常用的编程语言之一. 编写良好的 C++ 程序是快速.高效的. 该语言比其他语言更加灵活,因为你可以使用它来创建各种应用,包括有趣刺激的游戏.高性能科学软件.设备驱动程序.嵌入式程序 ...
 - C++ primer plus读书笔记——第16章 string类和标准模板库
		
第16章 string类和标准模板库 1. string容易被忽略的构造函数: string(size_type n, char c)长度为n,每个字母都为c string(const string ...
 - [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优 ...
 - 数据处理之CoreData
		
一.CoreData数据库框架与Sqlite对比 Sqlite: 1.基于C接口, 需要使用sql语句, 代码繁琐 2.在处理大量数据时, 表关系更直观 3.在OC中不是可视化的 CoreData: ...
 - 在SQL Server 2014里可更新的列存储索引 (Updateable Column Store Indexes)
		
传统的关系数据库服务引擎往往并不是对超大量数据进行分析计算的最佳平台,为此,SQL Server中开发了分析服务引擎去对大笔数据进行分析计算.当然,对于数据的存放平台SQL Server数据库引擎而言 ...
 - 为什么我会选IT【这几年是怎么过来的】
		
导火线 晚上跟高中同学说我近来的状况,无意中他提到:“如果当初没意外话,今年估计你就是一名老师了吧”.这让我很是怀念以前的日子,这四年来过的很快,开始想着当初是怎么过来的 : 高考 本人英语不佳,高考 ...
 
随机推荐
- 使用 Jersey 和 Apache Tomcat 构建 RESTful Web 服务
			
作者: Yi Ming Huang, 软件工程师, IBM Dong Fei Wu, 软件工程师, IBM Qing Guo, 软件工程师, IBM 出处: http://www.ibm.com/de ...
 - php 密码hash加密
			
做密码加密,记录一下. password_hash 函数在 PHP 5.5 时被引入. 此函数现在使用的是目前 PHP 所支持的最强大的加密算法 BCrypt .例子: $passwordHash = ...
 - C++函数传递数组的两种方式
			
数组与指针. 传首地址过去,然后通过地址输出数组元素. 1.一维数组 #include<iostream> using namespace std; #include <cstrin ...
 - Memcached的实战笔记
			
官网:http://memcached.org/ 优秀Blogs: http://blog.csdn.net/jingqiang521/article/details/48345021 开启telne ...
 - js-DOM操作基本知识
 - Nginx 实现反向代理
			
Nginx 实现反向代理 两个域名指向同一台 Nginx 服务器,用户访问不同的域名显示不同的网页内容 两个域名分别是 www.test1.com www.test2.com 1.准备工作 下载及安装 ...
 - Mysql怎么样避免全表扫描,sql查询优化
			
对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引: 尝试下面的技巧以避免优化器错选了表扫描: 使用ANALYZE TABLE tbl_name为扫 ...
 - 从100PV到1亿级PV站点架构演变
			
假设你对项目管理.系统架构有兴趣,请加微信订阅号"softjg".增加这个PM.架构师的大家庭 一个站点就像一个人,存在一个从小到大的过程. 养一个站点和养一个人一样.不同一时候期 ...
 - intellij idea 13&14 插件推荐及高速上手建议 (已更新!)
			
早些年 在外企的时候,公司用的是intellij idea ,当时也是从eclipse.MyEclipse转过去的非常是不习惯. 用了一周明显感觉爱上它了.由于它非常智能,并且能纠正你非常多不好的习惯 ...
 - 【甘道夫】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 ...