鱼C论坛

 找回密码
 立即注册
查看: 3274|回复: 4

关于集合问题

[复制链接]
发表于 2019-12-21 16:21:45 | 显示全部楼层
提供一个排序之后的算法,效率要高一些:
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;

  5. template <typename T>
  6. vector<T> operator-(vector<T> a, vector<T> b) {
  7.         sort(a.begin(), a.end());
  8.         sort(b.begin(), b.end());
  9.         vector<T> ret;
  10.         for (auto p = a.begin(), q = b.begin(); p != a.end(); ++p) {
  11.                 while (q != b.end() && *p > *q) {
  12.                         q++;
  13.                 }
  14.                 if (q != b.end() && *p == *q) {
  15.                         continue;
  16.                 }
  17.                 ret.push_back(*p);
  18.         }
  19.         return ret;
  20. }

  21. template <typename T>
  22. ostream& operator<<(ostream& os, vector<T> v) {
  23.         os << "{ ";
  24.         bool b = false;
  25.         for (const T& t : v) {
  26.                 if (b) {
  27.                         os << " , ";
  28.                 }
  29.                 os << t;
  30.                 b = true;
  31.         }
  32.         os << " }";
  33.         return os;
  34. }
  35. int main() {
  36.         vector<int> a = { 1,2,3,4,5,6 };
  37.         vector<int> b = { 2,4,5,6,7,8 };
  38.         vector<int> c = a - b;
  39.         cout << c << endl;
  40.         system("pause");
  41. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-12 03:09

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表