transform()

#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#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;

	transform(ivec.begin(), ivec.end(), ivec.begin(), negate<int>());  //negate<int>()是取反数运算,
	for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter)
		cout << *iter << ' ';
	cout << endl; // 输出是-1 -2 -3 -4 -5 -6 -7 -8 -9

	transform(ivec.begin(), ivec.end(), back_inserter(ilist), bind2nd(multiplies<int>(),10));
	//back_inserter 是iterator适配器,它使得元素被插入到作为实参的某种容器的尾部,如vector等.
	//multiplies是乘法将每个数乘以10,
	for (list<int>::iterator iter = ilist.begin(); iter != ilist.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;  // 输出是-10 -20 -30 -40 -50 -60 -70 -80 -90 

	transform(ilist.begin(), ilist.end(), ostream_iterator<int>(cout," "), negate<int>());
	// 输出是10 20 30 40 50 60 70 80 90

	return 0;
}

你可能感兴趣的:(transform())