首页 > STL编程 > STL四则运算仿函数

STL四则运算仿函数

STL中四则运算的仿函数算子分别是加plus<type>(), 减minus<type>(), 乘plus<type>(), 除plus<type>(),还有取模运算modulus<type>(),取反negate<type>().这些都定义在functional头文件中。下面通过transform的配合来介绍一下各个函数的用法:
先创建两个vector,都存放1到9,然后通过transform将两个集合中的元素进行相应的操作:

//Coded by 代码疯子
//http://www.programlife.net/
#include <iostream>
#include <iterator>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;

int main()
{
	vector<int> coll1;
	vector<int> coll2;
	
	for(int i = 1; i <= 9; ++i)
	{
		coll1.push_back(i);
		coll2.push_back(i);
	}
	
	cout << "coll1: ";
	copy(coll1.begin(), coll1.end(), ostream_iterator<int>(cout, " "));
	cout << endl;
	
	cout << "coll2: ";
	copy(coll2.begin(), coll2.end(), ostream_iterator<int>(cout, " "));
	cout << endl;
	
	vector<int> coll3(coll2);
	//plus
	cout << "After plus:" << endl;
	transform(coll1.begin(), coll1.end(),
			  coll2.begin(), coll3.begin(),
			  plus<int>());
	
	copy(coll3.begin(), coll3.end(), ostream_iterator<int>(cout, " "));
	cout << endl;
	//minus
	cout << "After minus:" << endl;
	transform(coll1.begin(), coll1.end(),
			  coll2.begin(), coll3.begin(),
			  minus<int>());
	
	copy(coll3.begin(), coll3.end(), ostream_iterator<int>(cout, " "));
	cout << endl;	
	//multiplies
	cout << "After multiplies:" << endl;
	transform(coll1.begin(), coll1.end(),
			  coll2.begin(), coll3.begin(),
			  multiplies<int>());
	
	copy(coll3.begin(), coll3.end(), ostream_iterator<int>(cout, " "));
	cout << endl;
	//divides
	cout << "After divides:" << endl;
	transform(coll1.begin(), coll1.end(),
			  coll2.begin(), coll3.begin(),
			  divides<int>());
	
	copy(coll3.begin(), coll3.end(), ostream_iterator<int>(cout, " "));
	cout << endl;
	//modulus
	cout << "After modulus:" << endl;
	transform(coll1.begin(), coll1.end(),
			  coll2.begin(), coll3.begin(),
			  modulus<int>());
	
	copy(coll3.begin(), coll3.end(), ostream_iterator<int>(cout, " "));
	cout << endl;
	
	return 0;
}

程序的运行结果截图如下:

STL function object


觉得文章还不错?点击此处对作者进行打赏!


本文地址: 程序人生 >> STL四则运算仿函数
作者:代码疯子(Wins0n) 本站内容如无声明均属原创,转载请保留作者信息与原文链接,谢谢!


更多



分类: STL编程 标签: , , ,
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.