预定义的函数对象
negate<type>() equal_to<type>()
plus<type>() not_equal_to<type>()
minus<type>() less<type>()
multiplies<type>() greater<type>()
divides<type>() less_equal<type>()
modulus<type>() greater_equal<type>()
logical_not<type>() logical_and<type>()
logical_or<type>()
#include<iostream> #include<algorithm> #include<vector> #include<list> #include<functional> #include<iterator> using namespace std; int main() { vector<int> ivec; list<int> ilist; for (int i = 1; i <= 9; i++) ivec.push_back(i); for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); iter++) { cout << *iter << ' '; } cout << endl; // negate 取负值 negate 预定义的函数对象 transform(ivec.begin(), ivec.end(), ivec.begin(), negate<int>()); for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); iter++) { cout << *iter << ' '; } cout << endl; // ilist 做变换的时候必须保证 ilist 有空间 // back_inserter 加上头文件 #include<iterator> transform(ivec.begin(), ivec.end(), back_inserter(ilist),bind2nd(multiplies<int>(), 10)); for (list<int>::iterator iter = ilist.begin(); iter != ilist.end(); iter++) { cout << *iter << ' '; } cout << endl; transform(ilist.begin(), ilist.end(), ostream_iterator<int>(cout, " "), negate<int>()); // system("pause"); return 0; }
第二种形式 融合数据
#include<iostream> #include<vector> #include<list> #include<algorithm> // #include<iterator> #include<functional> using namespace std; int main() { vector<int> ivec; list<int> ilist; for (int i = 1; i <= 9; i++) ivec.push_back(i); for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); iter++) cout << *iter << ' '; cout << endl; transform(ivec.begin(), ivec.end(), ivec.begin(), ivec.begin(), multiplies<int>()); for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); iter++) cout << *iter << ' '; cout << endl; // back_inserter 因为 ilist 是空的,所以我们要用插入迭代器 transform(ivec.begin(), ivec.end(), ivec.begin(), back_inserter(ilist), plus<int>()); for (list<int>::iterator iter = ilist.begin(); iter != ilist.end(); iter++) cout << *iter << ' '; cout << endl; transform(ivec.begin(), ivec.end(), ilist.begin(), ostream_iterator<int>(cout, " "), minus<int>()); // system("pause"); return 0; }
时间: 2024-10-13 23:57:31