C++ stl accumulate 函数的理解

首先看一个例程:

//eg.1
vector<int> vi{1, 2, 3};

cout << accumulate(vi.begin(), vi.end(), 0);    // 6

可以看出accumulate 有三个参数:

第一个是起点;第二个是终点,第三个是初始值。

  // eg.2
 int ptotal;
   ptotal = accumulate ( v3.begin ( ) , v3.end ( ) , 1 , multiplies<int>( ) );

 第二个例程中出现第四个参数,表示操作符,除了可以使用系统自带的加减乘除等操作外,还可以使用自定义的运算法则,如下例程3所示.

//eg.3
#include <vector>
#include <string>
using namespace std;
 
struct Grade
{
	string name;
	int grade;
};
 
int main()
{
	Grade subject[3] = {
		{ "English", 80 },
		{ "Biology", 70 },
		{ "History", 90 }
	};
 
	int sum = accumulate(subject, subject + 3, 0, [](int a, Grade b){return a + b.grade; });
	cout << sum << endl;
 
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qcxyliyong/article/details/82712091
今日推荐