std::accumulate 是 C++ 标准库中的累积算法,通过初始值和二元操作将容器元素归约为单一结果,支持自定义操作如乘积、字符串拼接、最大值查找及复杂对象处理,适用于函数式风格的聚合计算,但不适用于需副作用或提前退出的循环场景。

C++的
accumulate
std::accumulate
<numeric>
基本累加形式:
accumulate(first, last, init)
init
[first, last)
+
#include <iostream>
#include <vector>
#include <numeric> // For std::accumulate
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// 初始值为0,对vector中的所有元素进行累加
int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum: " << sum << std::endl; // 输出:Sum: 15
// 初始值为10,对vector中的所有元素进行累加
int sum_from_ten = std::accumulate(numbers.begin(), numbers.end(), 10);
std::cout << "Sum from ten: " << sum_from_ten << std::endl; // 输出:Sum from ten: 25
return 0;
}自定义操作形式:
accumulate(first, last, init, binary_op)
init
binary_op
accumulate
#include <iostream>
#include <vector>
#include <numeric> // For std::accumulate
#include <string> // For string concatenation
#include <functional> // For std::multiplies
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// 自定义乘法操作,计算乘积,初始值为1
long long product = std::accumulate(numbers.begin(), numbers.end(), 1LL, std::multiplies<long long>());
std::cout << "Product: " << product << std::endl; // 输出:Product: 120 (1*2*3*4*5)
std::vector<std::string> words = {"Hello", ", ", "world", "!"};
// 自定义字符串拼接操作,初始值为空字符串
std::string sentence = std::accumulate(words.begin(), words.end(), std::string(""),
[](const std::string& current_sum, const std::string& element) {
return current_sum + element;
});
std::cout << "Sentence: " << sentence << std::endl; // 输出:Sentence: Hello, world!
// 也可以使用lambda表达式实现更复杂的逻辑,例如统计偶数个数
int even_count = std::accumulate(numbers.begin(), numbers.end(), 0,
[](int count, int num) {
return count + (num % 2 == 0 ? 1 : 0);
});
std::cout << "Even count: " << even_count << std::endl; // 输出:Even count: 2
return 0;
}accumulate
实现
accumulate
ResultType operation(AccumulatedValueType current_sum, ElementType current_element)
当你提供一个自定义的
binary_op
accumulate
init
binary_op(当前累积值, 当前元素)
立即学习“C++免费学习笔记(深入)”;
举个例子,假设我们想计算一个
std::vector<double>
accumulate
accumulate
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm> // For std::max
int main() {
std::vector<double> data = {3.14, 1.618, 2.718, 0.577};
// 找出vector中的最大值
// 初始值可以设置为一个足够小的值,或者直接用第一个元素
// 这里我们用lambda表达式来做比较操作
double max_val = std::accumulate(data.begin() + 1, data.end(), data[0],
[](double current_max, double element) {
return std::max(current_max, element);
});
std::cout << "Max value: " << max_val << std::endl; // 输出:Max value: 3.14
// 也可以计算所有元素的平方和
double sum_of_squares = std::accumulate(data.begin(), data.end(), 0.0,
[](double current_sum, double element) {
return current_sum + (element * element);
});
std::cout << "Sum of squares: " << sum_of_squares << std::endl; // 输出:Sum of squares: 21.0664
return 0;
}这里,Lambda 表达式
[](double current_max, double element){ return std::max(current_max, element); }current_max
element
accumulate
accumulate
当我第一次接触
accumulate
优势:
accumulate
for
accumulate
for (int x : vec) sum += x;
sum
accumulate
std::accumulate
accumulate
std::reduce
accumulate
std::accumulate
局限性:
accumulate
accumulate
init
1
0
binary_op
for
accumulate
for
accumulate
accumulate
std::reduce
std::transform_reduce
总的来说,
accumulate
for
accumulate
accumulate
accumulate
binary_op
基本数据类型: 对于
int
double
float
accumulate
#include <iostream>
#include <vector>
#include <numeric>
int main() {
std::vector<double> prices = {19.99, 29.50, 5.00, 12.75};
double total_cost = std::accumulate(prices.begin(), prices.end(), 0.0);
std::cout << "Total cost: " << total_cost << std::endl; // 输出:Total cost: 67.24
return 0;
}字符串类型: 字符串拼接是
accumulate
std::string
+
accumulate
#include <iostream>
#include <vector>
#include <numeric>
#include <string>
int main() {
std::vector<std::string> parts = {"The ", "quick ", "brown ", "fox."};
std::string full_sentence = std::accumulate(parts.begin(), parts.end(), std::string(""));
std::cout << "Full sentence: " << full_sentence << std::endl; // 输出:Full sentence: The quick brown fox.
return 0;
}这里需要注意的是,如果
init
""
const char*
+
std::string("")自定义类或结构体: 这是
accumulate
accumulate
假设我们有一个
Product
#include <iostream>
#include <vector>
#include <numeric>
#include <string>
struct Product {
std::string name;
double price;
int quantity;
double get_value() const {
return price * quantity;
}
};
int main() {
std::vector<Product> inventory = {
{"Laptop", 1200.0, 5},
{"Mouse", 25.0, 50},
{"Keyboard", 75.0, 20}
};
// 计算总库存价值
// 初始值是0.0,累加的是每个产品的价值
double total_inventory_value = std::accumulate(inventory.begin(), inventory.end(), 0.0,
[](double current_total, const Product& p) {
return current_total + p.get_value();
});
std::cout << "Total inventory value: " << total_inventory_value << std::endl; // 输出:Total inventory value: 7650
return 0;
}在这个例子中,
accumulate
Product
Product
get_value()
accumulate
需要注意的细节:
accumulate
init
0
double
int
double
0.0
operator+
accumulate
binary_op
binary_op
总而言之,
accumulate
accumulate
以上就是C++ accumulate算法 累加与自定义操作的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号