当前位置:   article > 正文

C++基础(16)——STL常用算法(排序、拷贝和集合)_c++ copy set集合

c++ copy set集合

前言

本文介绍了C++中STL常用排序、拷贝和集合算法

9.3:常见的排序算法(sort、random_shuffle、merge、reverse)

9.3.1:sort

9.3.2:random_shuffle

将容器中的数据位置重新打乱,可以配合随机数种子使用

9.3.3:merge

两个容器元素合并,并存储到另一个容器中。使用时两个容器中的数据必须是有序的,要么都是降序要么都是升序,合并之后的容器中的数据也是有序的。

9.3.4:reverse

vector容器结合reverse实现字符串翻转

9.4:常见的拷贝和替换算法(copy、replace、replace_if、swap)

9.4.1:copy

将一个容器中的数据拷贝到另一个容器中

9.4.2:replace

将容器内指定范围的旧元素修改为新元素

9.4.3:replace_if

将区间内满足条件的元素替换成新元素

9.4.4:swap

将两个容器中的数据进行互换

9.5:常用算术生成算法(accumulate、fill)

accumulate函数原型,第三个参数是初值,可以设为0。计算容器中值的和

fill将容器中的元素都填充为一个值

9.6:常见集合算法(set_intersection、set_union、set_difference)

set_intersection
求两容器交集
set_union
求两个容器的并集
set_difference
求两个容器的差集

每个算法的返回结果都是集合最后一个元素的迭代器,要用这个迭代起来访问数据,如果不用返回的迭代器会访问到集合长度外的元素,就会出现默认的数据0。

  1. #include <iostream>
  2. #include <fstream>
  3. #include <string.h>
  4. #include <stdio.h>
  5. #include <vector>
  6. #include <algorithm>
  7. #include <queue>
  8. #include <list>
  9. #include <set>
  10. #include <map>
  11. #include <functional>
  12. #include <time.h>
  13. #include <numeric>
  14. using namespace std;
  15. void func(int val){
  16. cout << val << " ";
  17. }
  18. void printVector(const vector<int> &v){
  19. for(int i = 0; i < v.size(); i++){
  20. cout << v[i] << " ";
  21. }
  22. cout << endl;
  23. }
  24. int main()
  25. {
  26. vector<int> v1;
  27. for(int i = 0; i < 5; i++){
  28. v1.push_back(i);
  29. }
  30. cout << "v1数据:" << endl;
  31. printVector(v1);
  32. vector<int> v2;
  33. for(int i = 2; i < 9; i++){
  34. v2.push_back(i);
  35. }
  36. cout << "v2数据:" << endl;
  37. printVector(v2);
  38. vector<int> i_set;
  39. i_set.resize(min(v1.size(), v2.size()));
  40. vector<int>::iterator itEnd = set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), i_set.begin());
  41. cout << "交集数据:" << endl;
  42. for_each(i_set.begin(), itEnd, func);
  43. cout << endl;
  44. vector<int> u_set;
  45. u_set.resize(v1.size() + v2.size());
  46. vector<int>::iterator itEnd2 = set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), u_set.begin());
  47. cout << "并集数据:" << endl;
  48. for_each(u_set.begin(), itEnd2, func);
  49. cout << endl;
  50. vector<int> d_set;
  51. d_set.resize(max(v1.size(), v2.size()));
  52. vector<int>::iterator itEnd3 = set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), d_set.begin());
  53. cout << "针对v1差集数据:" << endl;
  54. for_each(d_set.begin(), itEnd3, func);
  55. cout << endl;
  56. vector<int> dd_set;
  57. dd_set.resize(max(v1.size(), v2.size()));
  58. vector<int>::iterator itEnd4 = set_difference(v2.begin(), v2.end(), v1.begin(), v1.end(), dd_set.begin());
  59. cout << "针对v2差集数据:" << endl;
  60. for_each(dd_set.begin(), itEnd4, func);
  61. cout << endl;
  62. }

代码运行结果

总结

以上是本文的全部内容,非常感谢你能看到这。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/920106
推荐阅读
相关标签
  

闽ICP备14008679号