现代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语句的更多相关文章

  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. HDU-2955 Robberies 浮点数01背包 自变量和因变量位置互换

    题目链接:https://cn.vjudge.net/problem/HDU-2955 题意 突然想找几个银行抢钱. 给出各银行的钱数和被抓的概率,以及能容忍的最大被抓概率. 问他最多能抢到多少钱? ...

  2. CF449D Jzzhu and Numbers (状压DP+容斥)

    题目大意: 给出一个长度为n的序列,构造出一个序列使得它们的位与和为0,求方案数 也就是从序列里面选出一个非空子集使这些数按位与起来为0. 看了好久才明白题解在干嘛,我们先要表示出两两组合位与和为0的 ...

  3. PHP的迭代器和生成器

    一.迭代器 分析:想一下,如果把集合对象和对集合对象的操作放在一起,当我们想换一种方式遍历集合对象中元素时,就需要修改集合对象了,违背"单一职责原则",而迭代器模式将数据结构和数据 ...

  4. 20121124.Nodejs异步式I/O与事件式编程

    异步: 你请人吃饭,准备一起去的.结果那人刚好有事,让你先去点菜,你去点好菜,他忙完就来了,这就是异步的优势(不耽误事!)同步: 就是,你必须等那个人忙完了,才一起去(浪费时间) 理解来源于群友&qu ...

  5. Spring的ApplicationContextAware接口的作用

    ApplicationContextAware接口: 当一个类实现了这个接口之后,这个类就可以方便地获得 ApplicationContext 中的所有bean.换句话说,就是这个类可以直接获取Spr ...

  6. IDEA使用操作说明(自己总结)

    1.idea导入一个项目后,如何再导入另一个项目 首先,点击File-->new-->Module from Existing Sources...-->找到该项目所在位置,选中该项 ...

  7. 使用iTools、PP助手清理垃圾前后文件夹对照图

    1.1 documents清理前 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveHl4am4=/font/5a6L5L2T/fontsize/400/fi ...

  8. Linux内核中进程上下文和中断上下文的理解

    參考: http://www.embedu.org/Column/Column240.htm http://www.cnblogs.com/Anker/p/3269106.html 首先明白一个概念: ...

  9. CreateProcess

    #include <Windows.h> //WINBASEAPI //BOOL //WINAPI //CreateProcessW( //_In_opt_ LPCWSTR lpAppli ...

  10. 查看typedef类型

    typedef unsigned long int NUM; #include <iostream> using namespace std; NUM x; cout << t ...