C++STL算法篇之集合算法

简介: C++STL算法篇之集合算法

集合算法

当然最好还是要包含

functional

algorithm

这2个头文件

集合算法有4个函数

1.set_union 交集

2.set_difference 差集

3.set_intersection 交集

4. set_symmetric_difference 对称差集

这4个函数的参数用法都差不多

set_union(并集)

就是求2个容器的并集,有5个参数,前4个参数分别为2个容器的范围,

最后一个参数可以是个输出流,直接打印出来,也可以存在第三个容器的起始位置

#include<iostream>
#include<functional>
#include<algorithm>
#include<string>
#include<vector>
using  namespace std;
int main()
{
  vector<int> date1{ 1, 2, 3, 4, 7, 8 };
  vector<int> date2{ 5, 6, 7, 8 };
  //1. set_union  并集算法
  //可以放到另一个容器中,也可以直接使用输出流打印出来
  set_union(date1.begin(), date1.end(), date2.begin(), date2.end(), ostream_iterator<int>(cout, " "));
  return 0;
}

set_difference(差集)

#include<iostream>
#include<functional>
#include<algorithm>
#include<string>
#include<vector>
using  namespace std;
int main()
{
  vector<int> date1{ 1, 2, 3, 4, 7, 8 };
  vector<int> date2{ 5, 6, 7, 8 };
  //2.set_difference 差集算法
  set_difference(date1.begin(), date1.end(), date2.begin(), date2.end(), ostream_iterator<int>(cout, " "));
  return 0;

set_intersection(交集)

#include<functional>
#include<algorithm>
#include<string>
#include<vector>
using  namespace std;
int main()
{
  vector<int> date1{ 1, 2, 3, 4, 7, 8 };
  vector<int> date2{ 5, 6, 7, 8 };
  //3.交集
  set_intersection(date1.begin(), date1.end(), date2.begin(), date2.end(), ostream_iterator<int>(cout, " "));
  cout << endl;
  return 0;
}

set_symmetric_difference(对称差集)

#include<iostream>
#include<functional>
#include<algorithm>
#include<string>
#include<vector>
using  namespace std;
int main()
{
  vector<int> date1{ 1, 2, 3, 4, 7, 8 };
  vector<int> date2{ 5, 6, 7, 8 };
  //4.对称差集算法 set_symetric_difference
  set_symmetric_difference(date1.begin(), date1.end(), date2.begin(), date2.end(),ostream_iterator<int>(cout," "));
  cout << endl;
  return 0;
}

集合算法讲解就到这里



相关文章
|
23天前
|
存储 算法 编译器
[C++] STL简介
[C++] STL简介
17 1
|
29天前
|
存储 算法 C++
C++ STL应用宝典:高效处理数据的艺术与实战技巧大揭秘!
【8月更文挑战第22天】C++ STL(标准模板库)是一组高效的数据结构与算法集合,极大提升编程效率与代码可读性。它包括容器、迭代器、算法等组件。例如,统计文本中单词频率可用`std::map`和`std::ifstream`实现;对数据排序及找极值则可通过`std::vector`结合`std::sort`、`std::min/max_element`完成;而快速查找字符串则适合使用`std::set`配合其内置的`find`方法。这些示例展示了STL的强大功能,有助于编写简洁高效的代码。
32 2
|
1月前
|
算法 C++ 容器
C++标准库中copy算法的使用
C++标准库中copy算法的使用
16 1
|
1月前
|
算法
突击面试:解密面试官的算法题集合
突击面试:解密面试官的算法题集合
|
1月前
|
算法 搜索推荐 C++
c++常见算法
C++中几种常见算法的示例代码,包括查找数组中的最大值、数组倒置以及冒泡排序算法。
16 0
|
1月前
|
安全 编译器 容器
C++STL容器和智能指针
C++STL容器和智能指针
|
1月前
|
算法 C++ 容器
【C++算法】双指针
【C++算法】双指针
|
1月前
|
算法 安全 Linux
|
2月前
|
设计模式 算法 Java
【c++】STL之stack和queue详解
【c++】STL之stack和queue详解
33 1
|
14天前
|
算法 BI Serverless
基于鱼群算法的散热片形状优化matlab仿真
本研究利用浴盆曲线模拟空隙外形,并通过鱼群算法(FSA)优化浴盆曲线参数,以获得最佳孔隙度值及对应的R值。FSA通过模拟鱼群的聚群、避障和觅食行为,实现高效全局搜索。具体步骤包括初始化鱼群、计算适应度值、更新位置及判断终止条件。最终确定散热片的最佳形状参数。仿真结果显示该方法能显著提高优化效率。相关代码使用MATLAB 2022a实现。