现代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【这几年是怎么过来的】
导火线 晚上跟高中同学说我近来的状况,无意中他提到:“如果当初没意外话,今年估计你就是一名老师了吧”.这让我很是怀念以前的日子,这四年来过的很快,开始想着当初是怎么过来的 : 高考 本人英语不佳,高考 ...
随机推荐
- 2.安装Cython
许多科学的Python发行版,例如Anaconda,Enthought Canopy和Sage,捆绑Cython并且不需要设置. 与大多数Python软件不同,Cython需要在系统上存在C编译器.获 ...
- 兴趣爱好-QQ的本地共享
QQ这个本地共享简直了,不就实现了公网FTP的功能么?好方便啊,有啥文件共享给好友就直接放在本地就可以了,真好用
- POJ 2041 Unreliable Message
简单模拟.依照题意处理一下字符串就可以. 应该是写题号写错了,本来我在VirtualJudge是加入的POJ 并查集与生成树的题. #include<cstdio> #include< ...
- 数据结构 - 树形选择排序 (tree selection sort) 具体解释 及 代码(C++)
树形选择排序 (tree selection sort) 具体解释 及 代码(C++) 本文地址: http://blog.csdn.net/caroline_wendy 算法逻辑: 依据节点的大小, ...
- Java生成验证码_转
为了防止用户恶意,或者使用软件外挂提交一些内容,就得用验证码来阻止,虽然这个会影响用户体验,但为了避免一些问题很多网站都使用了验证码;今天下午参考文档弄了一个验证码,这里分享一下;这是一个web工程, ...
- org.hibernate.AssertionFailure: null id in com.you.model.User entry (don't flush the Session after a
1.错误描写叙述 org.hibernate.AssertionFailure: null id in com.you.model.User entry (don't flush the Sessio ...
- swift学习第四章
// Playground - noun: a place where people can play import UIKit var age=100 //假设年龄不大于50的就会在这里断言,和之前 ...
- node21---mongoose
01.js //引包 var mongoose = require('mongoose'); //创建一个数据库连接 mongoose.connect('mongodb://localhost/tes ...
- 1.future线程通信
#include <future> #include<iostream> #include <thread> #include <thread> #in ...
- 移动端video播放时不弹出页面层
移动端视频在播放时会主动弹出页面,有的浏览器不会.对那些会的浏览器进行处理: 直接加上下面三个属性即可,兼容方面就不说了,微信上是很ok的. <video x5-playsinline=&quo ...