std::accumulate用于序列的累加或自定义规约操作,std::count用于统计特定值出现次数。前者支持自定义二元操作实现求和、乘积、字符串连接等复杂聚合,后者可结合count_if、map等实现条件计数与频率统计,二者均提升代码简洁性与可读性。

std::accumulate
std::count
std::accumulate
std::count
<numeric>
<algorithm>
accumulate
<numeric>
count
<algorithm>
std::accumulate
std::accumulate
它的基本形式是:
OutputIt accumulate(InputIt first, InputIt last, T init);
OutputIt accumulate(InputIt first, InputIt last, T init, BinaryOperation op);
这里,
first
last
init
op
std::plus<T>()
立即学习“C++免费学习笔记(深入)”;
示例:求和
#include <iostream>
#include <vector>
#include <numeric> // For std::accumulate
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// 求和
int sum = std::accumulate(numbers.begin(), numbers.end(), 0); // 初始值为0
std::cout << "Sum: " << sum << std::endl; // 输出:Sum: 15
// 注意init值对类型的影响
std::vector<double> prices = {10.5, 20.3, 5.2};
double total_price = std::accumulate(prices.begin(), prices.end(), 0.0); // 初始值为0.0,结果为double
std::cout << "Total Price: " << total_price << std::endl; // 输出:Total Price: 36
return 0;
}示例:自定义操作(乘积)
#include <iostream>
#include <vector>
#include <numeric>
#include <functional> // For std::multiplies
int main() {
std::vector<int> nums = {1, 2, 3, 4};
// 求乘积,初始值为1
int product = std::accumulate(nums.begin(), nums.end(), 1, std::multiplies<int>());
std::cout << "Product: " << product << std::endl; // 输出:Product: 24
// 使用lambda表达式连接字符串
std::vector<std::string> words = {"Hello", " ", "World", "!"};
std::string sentence = std::accumulate(words.begin(), words.end(), std::string(""),
[](const std::string& a, const std::string& b) {
return a + b;
});
std::cout << "Sentence: " << sentence << std::endl; // 输出:Sentence: Hello World!
return 0;
}std::count
std::count
它的基本形式是:
SizeT count(InputIt first, InputIt last, const T& value);
first
last
value
示例:计数
#include <iostream>
#include <vector>
#include <algorithm> // For std::count
int main() {
std::vector<int> scores = {85, 90, 78, 90, 95, 88, 90};
// 统计90出现的次数
int count_90 = std::count(scores.begin(), scores.end(), 90);
std::cout << "Number of 90s: " << count_90 << std::endl; // 输出:Number of 90s: 3
std::vector<char> letters = {'a', 'b', 'c', 'a', 'd', 'a'};
int count_a = std::count(letters.begin(), letters.end(), 'a');
std::cout << "Number of 'a's: " << count_a << std::endl; // 输出:Number of 'a's: 3
return 0;
}std::accumulate
这个问题我其实经常思考,毕竟一个简单的
for
std::accumulate
首先,它体现了STL的“算法与容器分离”哲学。当你看到
std::accumulate
accumulate
其次,
accumulate
再者,当聚合逻辑变得复杂时,
accumulate
accumulate
for
for (int x : numbers) sum += x;
accumulate
std::accumulate
std::accumulate
BinaryOperation op
连接异构数据或自定义对象: 假设你有一个学生对象列表,每个学生有姓名和分数,你想把所有学生的名字连接起来。
#include <iostream>
#include <vector>
#include <numeric>
#include <string>
struct Student {
std::string name;
int score;
};
int main() {
std::vector<Student> students = {
{"Alice", 90}, {"Bob", 85}, {"Charlie", 92}
};
// 连接所有学生的名字
std::string all_names = std::accumulate(students.begin(), students.end(), std::string("Students: "),
[](const std::string& current_names, const Student& s) {
return current_names + s.name + " ";
});
std::cout << all_names << std::endl; // 输出:Students: Alice Bob Charlie
// 计算总分
int total_score = std::accumulate(students.begin(), students.end(), 0,
[](int current_sum, const Student& s) {
return current_sum + s.score;
});
std::cout << "Total Score: " << total_score << std::endl; // 输出:Total Score: 267
return 0;
}计算加权平均值: 如果你有一系列数据点,每个点有其值和对应的权重,你可以用
accumulate
#include <iostream>
#include <vector>
#include <numeric>
#include <utility> // For std::pair
int main() {
std::vector<std::pair<double, double>> data_points = {
{10.0, 0.5}, // value, weight
{20.0, 0.3},
{5.0, 0.2}
};
// 计算加权和
double weighted_sum = std::accumulate(data_points.begin(), data_points.end(), 0.0,
[](double current_sum, const std::pair<double, double>& p) {
return current_sum + (p.first * p.second);
});
// 计算总权重
double total_weight = std::accumulate(data_points.begin(), data_points.end(), 0.0,
[](double current_weight, const std::pair<double, double>& p) {
return current_weight + p.second;
});
if (total_weight > 0) {
double weighted_average = weighted_sum / total_weight;
std::cout << "Weighted Average: " << weighted_average << std::endl; // 输出:Weighted Average: 12.5
} else {
std::cout << "Cannot calculate weighted average: total weight is zero." << std::endl;
}
return 0;
}这些例子展示了
accumulate
std::count
当我们谈到数据统计,
std::count
std::count
std::count_if
std::count
#include <iostream>
#include <vector>
#include <algorithm> // For std::count_if
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 统计偶数的个数
int even_count = std::count_if(numbers.begin(), numbers.end(),
[](int n) { return n % 2 == 0; });
std::cout << "Even numbers: " << even_count << std::endl; // 输出:Even numbers: 5
// 统计大于5的数字个数
int greater_than_5_count = std::count_if(numbers.begin(), numbers.end(),
[](int n) { return n > 5; });
std::cout << "Numbers greater than 5: " << greater_than_5_count << std::endl; // 输出:Numbers greater than 5: 5
return 0;
}count_if
std::for_each
std::for_each
#include <iostream>
#include <vector>
#include <algorithm> // For std::for_each
int main() {
std::vector<std::string> words = {"apple", "banana", "cat", "dog", "elephant"};
int words_with_a = 0;
// 统计包含字母'a'的单词,并打印它们
std::for_each(words.begin(), words.end(),
[&](const std::string& word) { // 注意这里需要捕获words_with_a
if (word.find('a') != std::string::npos) {
words_with_a++;
std::cout << "Found word with 'a': " << word << std::endl;
}
});
std::cout << "Total words with 'a': " << words_with_a << std::endl; // 输出:Total words with 'a': 3
return 0;
}这种方式的优点是可以在统计的同时执行其他操作,但缺点是需要一个可变的外部状态,不如
count_if
结合容器(如std::map
std::unordered_map
std::map
std::unordered_map
#include <iostream>
#include <vector>
#include <map> // For std::map
#include <string>
int main() {
std::vector<std::string> fruits = {"apple", "banana", "apple", "orange", "banana", "apple"};
std::map<std::string, int> frequency_map;
for (const std::string& fruit : fruits) {
frequency_map[fruit]++;
}
std::cout << "Fruit Frequencies:" << std::endl;
for (const auto& pair : frequency_map) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
// 输出:
// Fruit Frequencies:
// apple: 3
// banana: 2
// orange: 1
return 0;
}这种方法在需要全面了解数据分布时是无价的,它提供了一个“全景”的统计视图,而不仅仅是单一元素的计数。
总的来说,STL提供了一个工具箱,我们应该根据具体的统计需求来选择最合适的工具。
count
count_if
for_each
map
以上就是C++STL算法accumulate和count使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号