Zheng Chu's Blog

让希望永驻


  • 主页

  • 所有专栏

  • 历史文章

  • 标签

  • 关于我

累加累减容器中的元素

Posted on 2019-09-15 Edited on 2020-12-06 In C++ Views:

累加map中的元素

accumulate函数模板:

  • Returns the result of accumulating all the values in the range [first,last) to init

模板行为:

1
2
3
4
5
6
7
8
9
template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init)
{
while (first!=last) {
init = init + *first; // or: init=binary_op(init,*first) for the binary_op version
++first;
}
return init;
}

初始值为init,用它做累加或累减操作:

1
#include <functional>   // minus函数用来做累积减
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// accumulate example
#include <iostream> // std::cout
#include <functional> // std::minus
#include <algorithm> // std::accumulate
#include <map>
using namespace std;

struct addValues{
template<class Value, class Pair>
Value operator()(Value value, const Pair& pair) const
{
return value + pair.second;
}
};
int main () {
int init = 100;
map<int, int> table = {{10, 1}, {20,2}, {30,3}};

int value = accumulate(table.begin(), table.end(), init, addValues());
cout << "calulate using template: " << value << endl;

value = accumulate(table.begin(), table.end(), init,
[](auto value, const map<int, int>::value_type& p){return value + p.second;});
cout << "caculate by lambda function: " << value << endl;

int arr[] = {1, 3, 5, 7, 8};
value = accumulate(arr, next(arr, 5), init, minus<int>());
cout << "get minus numbers in array: " << value << endl;

vector<int> ivec = {1, 3, 5, 7, 8};
value = accumulate(ivec.begin(), ivec.end(), init, minus<int>());
cout << "get minus numbers in vector: " << value << endl;

return 0;
}

Output:
calulate using template: 106
caculate by lambda function: 106
get minus numbers in array: 76
get minus numbers in vector: 76
# Cooking
LeetCode-TopInterviewQuestions
CookingC++
  • Table of Contents
  • Overview
Zheng Chu

Zheng Chu

90 posts
20 categories
25 tags
GitHub 简书 CSDN E-Mail
  1. 1. 累加map中的元素
© 2021 Zheng Chu
Powered by Hexo v4.2.1
|
Theme – NexT.Pisces v7.3.0
|