Visual Studio 2010中C++的四大变化(1)
在微软即将发布的Visual Studio 2010正式版中,其对C++语言做了一些修改,之前51cto也报道过Visual Studio 2010中关于C++项目的升级问题,文章则针对C++语言上的一些变化。
Lambda表达式
很多编程编程语言都支持匿名函数(anonymous function)。所谓匿名函数,就是这个函数只有函数体,而没有函数名。Lambda表达式就是实现匿名函数的一种编程技巧,它为编写匿名函数提供了简明的函数式的句法。同样是Visual Studio中的开发语言,Visual Basic和Visual C#早就实现了对Lambda表达式的支持,终于Visual C++这次也不甘落后,在Visual Studio 2010中添加了对Lambda表达式的支持。
Lambda表达式使得函数可以在使用的地方定义,并且可以在Lambda函数中使用Lambda函数之外的数据。这就为针对集合操作带来了很大的便利。在作用上,Lambda表达式类似于函数指针和函数对象,Lambda表达式很好地兼顾了函数指针和函数对象的优点,却没有它们的缺点。相对于函数指针或是函数对象复杂的语法形式,Lambda表达式使用非常简单的语法就可以实现同样的功能,降低了Lambda表达式的学习难度,避免了使用复杂的函数对象或是函数指针所带来的错误。我们可以看一个实际的例子:
- #include "stdafx.h"
- #include <algorithm>
- #include <iostream>
- #include <ostream>
- #include <vector>
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- vector<int> v;
- for (int i = 0; i < 10; ++i) {
- v.push_back(i);
- }
- for_each(v.begin(), v.end(), [] (int n) {
- cout << n;
- if (n % 2 == 0) {
- cout << " even ";
- } else {
- cout << " odd ";
- }
- });
- cout << endl;
- return 0;
- }
- #include "stdafx.h"
- #include <algorithm>
- #include <iostream>
- #include <ostream>
- #include <vector>
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- vector<int> v;
- for (int i = 0; i < 10; ++i) {
- v.push_back(i);
- }
- for_each(v.begin(), v.end(), [] (int n) {
- cout << n;
- if (n % 2 == 0) {
- cout << " even ";
- } else {
- cout << " odd ";
- }
- });
- cout << endl;
- return 0;
- }
这段代码循环遍历输出vector中的每一个数,并判断这个数是奇数还是偶数。我们可以随时修改Lambda表达式而改变这个匿名函数的实现,修改对集合的操作。在这段代码中,C++使用一对中括号“[]”来表示Lambda表达式的开始,其后的”(int n)”表示Lambda表达式的参数。这些参数将在Lambda表达式中使用到。为了体会Lambda表达式的简洁,我们来看看同样的功能,如何使用函数对象实现:
- #include "stdafx.h"
- #include <algorithm>
- #include <iostream>
- #include <ostream>
- #include <vector>
- using namespace std;
- struct LambdaFunctor {
- void operator()(int n) const {
- cout << n << " ";
- if (n % 2 == 0) {
- cout << " even ";
- } else {
- cout << " odd ";
- }
- }
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- vector<int> v;
- for (int i = 0; i < 10; ++i) {
- v.push_back(i);
- }
- for_each(v.begin(), v.end(), LambdaFunctor());
- cout << endl;
- return 0;
- }
- #include "stdafx.h"
- #include <algorithm>
- #include <iostream>
- #include <ostream>
- #include <vector>
- using namespace std;
- struct LambdaFunctor {
- void operator()(int n) const {
- cout << n << " ";
- if (n % 2 == 0) {
- cout << " even ";
- } else {
- cout << " odd ";
- }
- }
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- vector<int> v;
- for (int i = 0; i < 10; ++i) {
- v.push_back(i);
- }
- for_each(v.begin(), v.end(), LambdaFunctor());
- cout << endl;
- return 0;
- }
通过比较我们就可以发现,Lambda表达式的语法更加简洁,使用起来更加简单高效。
- 上一篇:C++详解 引用的应用
- 下一篇:C++编译器的函数编译流程