admin 管理员组文章数量: 1103785
不造轮子之STL中统计算法
在日常的开发中,常涉及到容器的常见操作,如查找、删除、排序等,C++ STL提供了丰富的算法库,可以方便的完成这些操作。为了避免重复造轮子,同时为了提高效率,了解常见的STL算法是非常有必要的。本文将介绍统计相关算法。
1. std::all_of
功能:检查范围内的所有元素是否都满足某个条件。
代码语言:javascript代码运行次数:0运行复制#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector vec = {2, 4, 6, 8};
bool all_even = std::all_of(vec.begin(), vec.end(),
[](int i){ return i % 2 == 0; });
std::cout << (all_even ?
"All are even" : "Not all are even") << std::endl;
}
解读:std::all_of 函数检查容器中的所有元素是否都满足lambda表达式中的条件。
2. std::any_of
功能:检查范围内的任意一个元素是否满足某个条件。
代码语言:javascript代码运行次数:0运行复制#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector vec = {1, 3, 5, 7};
bool any_odd = std::any_of(vec.begin(), vec.end(),
[](int i){ return i % 2 != 0; });
std::cout << (any_odd ? "At least one is odd" : "All are even") << std::endl;
}
解读:std::any_of 函数检查容器中是否存在至少一个元素满足lambda表达式中的条件。
3. std::none_of
功能:检查范围内的所有元素是否都不满足某个条件。
代码语言:javascript代码运行次数:0运行复制#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector vec = {2, 4, 6, 8};
bool none_odd = std::none_of(vec.begin(), vec.end(),
[](int i) { return i % 2 != 0; });
std::cout << (none_odd ?
"None are odd" : "At least one is odd") << std::endl;
}
解读:std::none_of 函数检查容器中的所有元素是否都不满足lambda表达式中的条件。
4. std::count
功能:统计范围内满足某个条件的元素个数。
代码语言:javascript代码运行次数:0运行复制#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector vec = {1, 2, 3, 2, 4, 2, 5};
int count = std::count(vec.begin(), vec.end(), 2);
std::cout << "Count of 2: " << count << std::endl;
}
解读:std::count 函数统计容器中等于指定值的元素个数。
5. std::count_if
功能:统计范围内满足某个条件的元素个数。
代码语言:javascript代码运行次数:0运行复制#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector vec = {1, 2, 3, 4, 5};
int count = std::count_if(vec.begin(), vec.end(),
[](int i){ return i % 2 == 0; });
std::cout << "Count of even numbers: " << count << std::endl;
}
解读:std::count_if 函数统计容器中满足lambda表达式条件的元素个数。
总结
本文介绍了C++ STL中统计相关算法,包括std::all_of、std::any_of、std::none_of、std::count和std::count_if,这些算法可以帮助我们方便地完成对容器中元素的统计操作。
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。原始发表:2024-09-30,如有侵权请联系 cloudcommunity@tencent 删除函数算法统计容器stl本文标签: 不造轮子之STL中统计算法
版权声明:本文标题:不造轮子之STL中统计算法 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.520sys.cn/xp/1755046895a1463075.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论