
C++ STL 函数用于集合操作
集合操作是编程中常见且重要的操作。C++ 标准模板库 (STL) 提供了大量的函数来帮助您执行各种集合操作。本文将重点介绍这些函数,并提供一些实战案例。
并集和交集
set_union:计算两个集合的并集。set_intersection:计算两个集合的交集。案例:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <set>
using namespace std;
int main() {
// 创建两个集合
set<int> set1 = {1, 2, 3, 4, 5};
set<int> set2 = {2, 4, 6, 8, 10};
// 计算并集
set<int> 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<int> 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 <iostream>
#include <set>
using namespace std;
int main() {
// 创建两个集合
set<int> set1 = {1, 2, 3, 4, 5};
set<int> set2 = {2, 4, 6, 8, 10};
// 计算差集
set<int> 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<int> 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 函数有哪些用于集合操作?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号