C++ foreach
考虑下面的需求,对vector<int>中的每个元素加1,如何做?
void add(int& lhs) // 注意:要修改主调方法中的数据,这里要使用引用 { lhs= lhs + 1; } int intArray[] = {1,2,3,4,5}; vector<int> intVector(intArray,intArray+5);
1、最原始的做法:
for(vector<int>::iterator iter=intVector.begin();iter!=intVector.end();iter++) { add(*iter); }
2、使用类似boost中的foreach
// 注意:要修改intVector中的元素,这里要使用引用,遍历intVector的元素,用每个元素初始化引用a // 因为这种情况下,遍历intVector的时候,是间接地使用intVector中的元素。 BOOST_FOREACH(int& a,intVector) { add(a); }
3、使用for_each
1 for_each(intVector.begin(),intVector.end(),add);
for_each表达的意义是对intVector的每个元素执行add方法,用(*iter)初始化add的形参。
考虑下面的需求,对vector<int>中的每个元素加一个变量,如何做?
void add(int& lhs,int rhs) { lhs= lhs + rhs; }
对于第一种方法和第二种方法,很简单,直接使用对应的方法就行了。对于第三种方法怎么办呢?
也就是说,如何把变量传给形参rhs?
考虑 for_each(intVector.begin(),intVector.end(),add); 实际上等价于
for_each(intVector.begin(),intVector.end(),boost::bind(add,_1));
因此,对于这种需求,就是 for_each(intVector.begin(),intVector.end(),boost::bind(add,_1,100));
-----------------------------------
boost::lexical_cast为数值之间的转换(conversion)提供了一揽子方案,比如:将一个字符串"123"转换成整数123,代码如下:
- string s = "123";
- int a = lexical_cast<int>(s);
这种方法非常简单,笔者强烈建议大家忘掉std诸多的函数,直接使用boost:: lexical_cast。如果转换发生了意外,lexical_cast会抛出一个bad_lexical_cast异常,因此程序中需要对其进行捕捉。
现在动手
编写如下程序,体验如何使用boost:: lexical_cast完成数值转换。
【程序 4-11】使用boost:: lexical_cast完成对象数值转换
- 01 #include "stdafx.h"
- 02
- 03 #include <iostream>
- 04 #include <boost/lexical_cast.hpp>
- 05
- 06 using namespace std;
- 07 using namespace boost;
- 08
- 09 int main()
- 10 {
- 11 string s = "123";
- 12 int a = lexical_cast<int>(s);
- 13 double b = lexical_cast<double>(s);
- 14
- 15 printf("%d/r/n", a + 1);
- 16 printf("%lf/r/n", b + 1);
- 17
- 18 try
- 19 {
- 20 int c = lexical_cast<int>("wrong number");
- 21 }
- 22 catch(bad_lexical_cast & e)
- 23 {
- 24 printf("%s/r/n", e.what());
- 25 }
- 26
- 27 return 0;28 }
如上程序实现字符串"123"到整数、双精度实数的转换(为了防止程序作弊,我们特意让它将值加1),结果输出如图4-19所示。