#include <iostream>
#include <vector>
#include <algorithm>
// 定义一个模板函数
template<class TF>
void general( std::vector<int>::iterator begin,
std::vector<int>::iterator end,
TF f ) {
std::vector<int>::iterator itr;
for(itr = begin; itr != end; itr++) {
f(*itr);
}
}
void add( int &rr ) {
++rr;
}
void output(const int &rr) {
std::cout << rr << " ";
}
void test01() {
std::vector<int> v;
v.push_back(10);
v.push_back(3);
v.push_back(4);
general(v.begin(), v.end(), add);
general(v.begin(), v.end(), output);
std::cout << std::endl;
std::cout << "系统函数 for_each : " << std::endl;
for_each(v.begin(), v.end(), add);
for_each(v.begin(), v.end(), output);
std::cout << std::endl;
std::cout << "test01 end ......" << std::endl;
}
template<class T1, class T2>
void merge(T1 a[], T1 b[], T1 c[], int size, T2 f) {
for (int i = 0; i < size; ++i) {
c[i] = f(a[i], b[i]);
}
}
// 函数对象的使用
void test02() {
std::string s1[3] = {"aa", "bb", "cc"};
std::string s2[3] = {"xx", "yy", "zz"};
std::string s3[3];
merge(s1, s2, s3, 3, std::plus<std::string>()); // 包 functional
for (int i = 0; i < 3; ++i) {
std::cout << s3[i] << std::endl;
}
std::cout << "s2 length ??? : " << s2->length() << std::endl;
std::cout << "test02 end ......" << std::endl;
}
int main() {
test01();
test02();
return 0;
}
网友评论