首页 > 其他 > 详细

STL之数值算法

时间:2014-04-16 12:35:29      阅读:499      评论:0      收藏:0      [点我收藏+]

STL之数值算法

必须包含头文件<numeric>
#include <numeric>
#include <vector>
#include <functional>
#include <iostream>
#include <iterator> //ostream_iterator
using namespace std;

int main()
{
	int ia[5] = {1,2,3,4,5};
	vector<int> iv(ia, ia+5);

	cout << accumulate(iv.begin(), iv.end(), 0) << endl;
	//15, i.e. 0+1+2+3+4+5

	cout << accumulate(iv.begin(), iv.end(), 0, minus<int>()) << endl;
	//-15 i.e. 0-1-2-3-4-5

	cout << inner_product(iv.begin(), iv.end(), iv.begin(), 10) << endl;
	//65, i.e. 10+1*1+2*2+3*3+4*4+5*5

	cout << inner_product(iv.begin(), iv.end(), iv.begin(), 10, 
		minus<int>(),plus<int>())<<endl;
	//-20, i.e 10 - (1+1)- (2+2)- (3+3)- (4+4)- (5+5)

	//以下这个迭代器将绑定到cout,作为输出
	ostream_iterator<int> oite(cout, " ");
	
	partial_sum(iv.begin(), iv.end(), oite);
	//1 3 6 10 15(第n个新元素是前n个旧元素的相加总计)

	partial_sum(iv.begin(), iv.end(), oite, minus<int>());
	//1 -1 -4 -8 -13(第n个新元素是前n个旧元素的运算总计)

	adjacent_difference(iv.begin(), iv.end(), oite);
	//1 1 1 1 1(#1元素照录,#n新元素等于#n旧元素-#n-1旧元素)

	adjacent_difference(iv.begin(), iv.end(), oite, plus<int>());
	//1 3 5 7 9(#1元素照录,#n新元素等于op(#n旧元素,#n-1旧元素))

	//以下函数时SGI专属
	//cout<<power(10,3)<<endl;	//1000, i.e. 10*10*10
	//cout<< power(10,3,plus<int>())<< endl;	//30, i.e. 10+10+10

	//int n = 3;
	//iota(iv.begin(), iv.end(), n);	//在指定区间内填入n,n+1,n+2

	//for(int i=0, i< iv.size(), ++i)
	//	cout << iv[i] << ‘ ‘	//3 4 5 6 7

	return 0;
}


STL之数值算法,布布扣,bubuko.com

STL之数值算法

原文:http://blog.csdn.net/walkerkalr/article/details/23736105

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!