OOP
不像过程性编程那样,使问题满足语言的过程性方法,而是使语言满足问题的要求。OOP首先设计类,准确表示程序要处理的东西。OOP编程不仅仅是将数据和方法合并为类定义。例如:利于创建可重用性代码;信息隐藏保护数据;多态使运算符和函数创建多个定义;继承使用旧类派生出新类等。
泛型编程
OOP强调的是编程的数据方面,而泛型编程强调的是独立于特定数据类型。OOP是管理大型项目的工具,泛型编程提供了执行常见任务(如:排序等)的工具。
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool F3(int x)
{
return x % 3 == 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> vec(100);
generate(vec.begin(), vec.end(), rand);
auto it = vec.begin();
for (; it != vec.end(); ++it)
{
cout << *it << endl;
}
return 0;
}
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool F3(int x)
{
return x % 3 == 0;
}
bool F13(int x)
{
return x % 13 == 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> vec(100);
generate(vec.begin(), vec.end(), rand);
int nCnt = count_if(vec.begin(), vec.end(), F3);
cout << nCnt << endl;
nCnt = count_if(vec.begin(), vec.end(), F13);
cout << nCnt << endl;
return 0;
}
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class CFn
{
public:
CFn(int x) : n(x)
{
}
bool operator()(int x)
{
return x%n == 0;
}
private:
int n;
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> vec(100);
generate(vec.begin(), vec.end(), rand);
int nCnt = count_if(vec.begin(), vec.end(), CFn(3));
cout << nCnt << endl;
nCnt = count_if(vec.begin(), vec.end(), CFn(13));
cout << nCnt << endl;
return 0;
}
方法三:lambda
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> vec(100);
generate(vec.begin(), vec.end(), rand);
int nCnt = count_if(vec.begin(), vec.end(),
[](int x)
{
return x % 3 == 0;
}
);
cout << nCnt << endl;
nCnt = count_if(vec.begin(), vec.end(),
[](int x)
{
return x % 13 == 0;
}
);
cout << nCnt << endl;
return 0;
}
有名称的lambda:
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> vec(100);
generate(vec.begin(), vec.end(), rand);
auto L3 = [](int x)
{
return x % 3 == 0;
};
int nCnt = count_if(vec.begin(), vec.end(), L3);
cout << nCnt << endl;
return 0;
}
这三种方法的相对效率取决于编译器内联那些东西。函数指针方法阻止内联,因为编译器传统上不会内联其地址被获取的函数,因为函数地址的概念意味着非内联函数。而函数符和lambda通常不会阻止内联。
lambda的额外功能:
lambda可访问函数内的任何动态变量;要捕获要使用的变量,把名称放入中括号内;如:[z],将按值访问变量。
如果在名称前加上&,如[&cnt],将按引用访问变量,[&]让您能按引用访问所有动态变量。[=]让您能按值访问所有动态变量,还可以混合使用,例如:[ted,&ed]按值访问ted,按引用访问ed; 而[&,ted]按引用访问所有动态变量,按值访问ted。
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> vec(100);
generate(vec.begin(), vec.end(), rand);
auto L3 = [](int x)
{
return x % 3 == 0;
};
int nCnt3 = 0;
int nCnt13 = 0;
for_each(vec.begin(), vec.end(),
[&](int x)
{
nCnt3 += (x % 3 == 0);
nCnt13 += (x % 13 == 0);
}
);
cout << nCnt3 << endl;
cout << nCnt13 << endl;
return 0;
}