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;
}

集合算法讲解就到这里



相关文章
|
29天前
|
算法 C++ 容器
C++标准库中copy算法的使用
C++标准库中copy算法的使用
14 1
|
14天前
|
存储 算法 编译器
[C++] STL简介
[C++] STL简介
11 1
|
21天前
|
存储 算法 C++
C++ STL应用宝典:高效处理数据的艺术与实战技巧大揭秘!
【8月更文挑战第22天】C++ STL(标准模板库)是一组高效的数据结构与算法集合,极大提升编程效率与代码可读性。它包括容器、迭代器、算法等组件。例如,统计文本中单词频率可用`std::map`和`std::ifstream`实现;对数据排序及找极值则可通过`std::vector`结合`std::sort`、`std::min/max_element`完成;而快速查找字符串则适合使用`std::set`配合其内置的`find`方法。这些示例展示了STL的强大功能,有助于编写简洁高效的代码。
30 2
|
1月前
|
算法
突击面试:解密面试官的算法题集合
突击面试:解密面试官的算法题集合
|
22天前
|
算法 搜索推荐 C++
c++常见算法
C++中几种常见算法的示例代码,包括查找数组中的最大值、数组倒置以及冒泡排序算法。
14 0
|
27天前
|
安全 编译器 容器
C++STL容器和智能指针
C++STL容器和智能指针
|
29天前
|
算法 C++ 容器
【C++算法】双指针
【C++算法】双指针
|
29天前
|
算法 安全 Linux
|
2月前
|
设计模式 算法 Java
【c++】STL之stack和queue详解
【c++】STL之stack和queue详解
31 1
|
2月前
|
存储 算法 C++
C++中集合的使用
C++中集合的使用