
集合操作是编程中常见且重要的操作。C++ 标准模板库 (STL) 提供了大量的函数来帮助您执行各种集合操作。本文将重点介绍这些函数,并提供一些实战案例。
并集和交集
set_union:计算两个集合的并集。set_intersection:计算两个集合的交集。
案例:
立即学习“C++免费学习笔记(深入)”;
#include #include using namespace std;int main() { // 创建两个集合 set set1 = {1, 2, 3, 4, 5}; set set2 = {2, 4, 6, 8, 10}; // 计算并集 set union_set; set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(union_set, union_set.begin())); // 输出并集 cout << "并集:" << endl; for (auto& element : union_set) { cout << element << " "; } cout << endl; // 计算交集 set intersection_set; set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(intersection_set, intersection_set.begin())); // 输出交集 cout << "交集:" << endl; for (auto& element : intersection_set) { cout << element << " "; } cout << endl; return 0;}
差集和对称差集
set_difference:计算两个集合的差集。set_symmetric_difference:计算两个集合的对称差集。
案例:
立即学习“C++免费学习笔记(深入)”;
#include #include using namespace std;int main() { // 创建两个集合 set set1 = {1, 2, 3, 4, 5}; set set2 = {2, 4, 6, 8, 10}; // 计算差集 set difference_set; set_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(difference_set, difference_set.begin())); // 输出差集 cout << "差集:" << endl; for (auto& element : difference_set) { cout << element << " "; } cout << endl; // 计算对称差集 set symmetric_difference_set; set_symmetric_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(symmetric_difference_set, symmetric_difference_set.begin())); // 输出对称差集 cout << "对称差集:" << endl; for (auto& element : symmetric_difference_set) { cout << element << " "; } cout << endl; return 0;}
以上就是C++ 函数的 STL 函数有哪些用于集合操作?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1460732.html
微信扫一扫
支付宝扫一扫