现代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 undesirable
cout << 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 10
Test 2 : 1 2 3 4 5 6 7 8 9 10
Test 3 : 1 2 3 4 5 6 7 8 9 10
Test 4 : 1 2 3 4 5 6 7 8 9 10
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语句,其语句形式为:
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 Factor
template <class Type>
class MultValue
{
private:
Type Factor; // The value to multiply by
public:
// Constructor initializes the value to multiply by
MultValue ( const Type& _Val ) : Factor ( _Val ) {
}
// The function call for the element to be multiplied
void operator ( ) ( Type& elem ) const
{
elem *= Factor;
}
};
// The function object to determine the average
class Average
{
private:
long num; // The number of elements
long sum; // The sum of the elements
public:
// Constructor initializes the value to multiply by
Average ( ) : num ( 0 ) , sum ( 0 )
{
}
// The function call to process the next elment
void operator ( ) ( int elem ) \
{
num++; // Increment the element count
sum += elem; // Add the value to the partial sum
}
// return Average
operator 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 v1
int 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 Factor
for_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 Factor
for_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 Average
double 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 v1
by the factor -2 gives:
v1mod1 = ( 8 6 4 2 0 -2 -4 ).
Multiplying the elements of the vector v1mod
by 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【这几年是怎么过来的】
导火线 晚上跟高中同学说我近来的状况,无意中他提到:“如果当初没意外话,今年估计你就是一名老师了吧”.这让我很是怀念以前的日子,这四年来过的很快,开始想着当初是怎么过来的 : 高考 本人英语不佳,高考 ...
随机推荐
- 使用ajax实现搜索功能
最近要做一个搜索功能,网上搜了一圈,终于做出来了,很简单的一个,这里分享我的方法,希望对大家有用,不足之处还请指教. 这里使用ajax提交数据,配合jquery将数据显示出来. 用jq的keyup ...
- zabbbix4.0升级到4.2
一.添加Zabbix存储库 1.安装存储库配置包. rpm -ivh https://repo.zabbix.com/zabbix/4.2/rhel/7/x86_64/zabbix-release-4 ...
- code-reading-notes--libyang-1
API struct lyd_node * lyd_parse_xml(struct ly_ctx *ctx, struct lyxml_elem **root, int options, ...) ...
- MongoDB入门 常用命令以及增删改查的简单操作
1,运行MongoDB服务mongod --dbpath=/usr/local/developmentTool/mongo/data/db/然后启动客户端mongo2,sudo service mon ...
- ArcGIS 安装
百度网盘下载链接 密码:tvm6 打开解压的文件后,第一步为安装licence manager(安装监听) 打开\ArcGIS10.4\LicenseManager中的Setup.exe 傻瓜式安装 ...
- MgdDbg工具
ArxDbg是可以查看AutoCAD内部数据结构的工具,可惜是C++的.从网上找到了一个.NET版本的MgdDbg,实现的功能与C++版本的差不多. 1.运行程序,你只要右键点击AutoCAD窗口,在 ...
- 利用Python对文件进行批量重命名
最近几天工作的内容是对40个项目进行考核,每个项目都需要一个考核评分表,已经有了项目的列表. 如果用常规的方法,需要复制40个文件,并逐个修改,不光工作量大,也容易出错,后期修改也不方便. 于是想到了 ...
- java中的hachcode方法
哈希表这个数据结构想必大多数人都不陌生,而且在很多地方都会利用到hash表来提高查找效率.在Java的Object类中有一个方法: public native int hashCode(); 根据这个 ...
- maven 构建web项目
Maven规定,必须创建以下几个Source Folder src/main/resources src/main/Java src/test/resources src/test/java 添加以上 ...
- 【转载】tslib移植_freescale imx6
本文来自网络:http://blog.csdn.net/xishuang_gongzi/article/details/49422879 环境:host:Ubuntu12.04target:frees ...