函数原型 template<class InIt, class OutIt, class Unop> OutIt transform(InIt first, InIt last, OutIt x, Unop uop) 即:*(x+N) = uop(*(first+N)), N c-[0, last-first) template<class InIt1, class InIt2, class OutIt, class Binop> 即:*(x+N)=bop(*(first1+N),*(first2+N)),N c-[0, last1-first1) transform简单示例 #include <iostream> #include <vector> #include <iterator> #include <algorithm> #include <cstdlib> #include <functional> using namespace std; int func1(int value) { return value * 2; } int func2(int value1, int value2) { return value1 + value2; } int main(int argc, char *argv[]) { int a[5] = {1, 2, 3, 4, 5}; vector<int> v1(a, a+5); vector<int> v2(5); cout << "原始向量v1 = "; copy(v1.begin(), v1.end(), ostream_iterator<int>(cout, " ")); cout << endl; cout << "v1 * 2 --> v1 = "; transform(v1.begin(), v1.end(), v1.begin(), func1); transform(v1.begin(), v1.end(), v1.begin(), bind2nd(multiplies<int>(), 2)); copy(v1.begin(), v1.end(), ostream_iterator<int>(cout, " ")); cout << endl; cout << "v1 * 2 --> v2 = "; transform(v1.begin(), v1.end(), v2.begin(), func1); transform(v1.begin(), v1.end(), v2.begin(), bind2nd(multiplies<int>(), 2)); copy(v2.begin(), v2.end(), ostream_iterator<int>(cout, " ")); cout << endl; int a2[5] = {1, 2, 3,4, 5}; int b2[5] = {6, 7, 8, 9, 10}; int c2[5]; cout << "a2[5] = "; copy(a2, a2 + 5, ostream_iterator<int>(cout, " ")); cout << endl; cout << "b2[5] = "; copy(b2, b2 + 5, ostream_iterator<int>(cout, " ")); cout << endl; cout << "a2 + b2 --> c2 = "; transform(a2, a2 + 5, b2, c2, func2); transform(a2, a2 + 5, b2, c2, plus<int>()); copy(c2, c2 + 5, ostream_iterator<int>(cout, " ")); cout << endl; system("pause"); return 0; } transform_Encrypt #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <fstream> #include <iterator> using namespace std; template<class T> class Encrypt { }; template<> //模板特化 class Encrypt<string> { public: string operator()(const string & src) { string s = src; int len = s.length(); for (string::iterator it = s.begin(); it != s.end(); it++) { *it = *it + 1; } return s; } }; int main(int argc, char *argv[]) { string strText; vector<string> v; vector<string> vResult; ifstream in("data.txt"); cout << "原文如下所示:" << endl; cout <<"___________________________________________________" << endl; if(!in.fail()) { while(!in.eof()) { getline(in, strText, '/n'); //一次read一行,不包括'/n' cout << strText << endl; v.push_back(strText); } } in.close(); cout << "___________________________________________________" << endl; transform(v.begin(), v.end(), back_inserter(vResult), Encrypt<string>()); copy(vResult.begin(), vResult.end(), ostream_iterator<string>(cout ,"/n")); system("pause"); return 0; }