简化对容器中元素的循环操作:
std::any_of用于检查是否有任何元素满足给定条件
std::all_of用于检查容器中的所有元素是否都满足条件
std::count_if用于统计满足条件的元素个数
std::transform用于对一个序列中的每个元素进行转换,并将结果存储到另一个序列中
#include <iostream>
#include <vector>
#include <algorithm>
bool CHECK_DATA(int value) {
// 这里可以根据实际情况编写条件判断的函数
return value % 2 == 0;
}
int main() {
std::vector<int> result = {1, 2, 3, 4, 5};
// 使用 std::any_of
if (std::any_of(result.begin(), result.end(), CHECK_DATA)) {
std::cout << "At least one element satisfies the condition." << std::endl;
} else {
std::cout << "No elements satisfy the condition." << std::endl;
}
// 使用 std::all_of
if (std::all_of(result.begin(), result.end(), CHECK_DATA)) {
std::cout << "All elements satisfy the condition." << std::endl;
} else {
std::cout << "Not all elements satisfy the condition." << std::endl;
}
int nums = std::count_if(result.begin(), result.end(),
[](const auto& res) { return CHECK_DATA(res); });
std::cout << "NUMS = " << nums << std::endl;
return 0;
}
At least one element satisfies the condition.
Not all elements satisfy the condition.
NUMS = 2
std::unordered_map<std::string, ComplexMat> mat_set;
std::vector<ComplexMat> res;
res.reserve(mat_set.size());
std::transform(mat_set.begin(), mat_set.end(), std::back_inserter(res),
[](const auto& pair) { return pair.second; });
这段代码使用了lambda表达式作为std::transform函数的第四个参数,用于将mat_set中的所有ComplexMat对象存储到res向量中。
#include <iostream>
#include <vector>
#include <algorithm>
void myFunction(int n) {
std::cout << n << " ";
}
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// 对容器中的每个元素应用指定的函数
std::for_each(numbers.begin(), numbers.end(), [](int n) {
std::cout << n * 2 << " ";
});
return 0;
}
本文介绍了C++中几个标准库算法,如std::any_of、std::all_of、std::count_if和std::transform,以及如何使用lambda表达式简化对容器元素的操作,包括检查条件、计数和转换。

2109

被折叠的 条评论
为什么被折叠?



