|
发表于 2019-12-21 16:21:45
|
显示全部楼层
提供一个排序之后的算法,效率要高一些:- #include <iostream>
- #include <vector>
- #include <algorithm>
- using namespace std;
- template <typename T>
- vector<T> operator-(vector<T> a, vector<T> b) {
- sort(a.begin(), a.end());
- sort(b.begin(), b.end());
- vector<T> ret;
- for (auto p = a.begin(), q = b.begin(); p != a.end(); ++p) {
- while (q != b.end() && *p > *q) {
- q++;
- }
- if (q != b.end() && *p == *q) {
- continue;
- }
- ret.push_back(*p);
- }
- return ret;
- }
- template <typename T>
- ostream& operator<<(ostream& os, vector<T> v) {
- os << "{ ";
- bool b = false;
- for (const T& t : v) {
- if (b) {
- os << " , ";
- }
- os << t;
- b = true;
- }
- os << " }";
- return os;
- }
- int main() {
- vector<int> a = { 1,2,3,4,5,6 };
- vector<int> b = { 2,4,5,6,7,8 };
- vector<int> c = a - b;
- cout << c << endl;
- system("pause");
- }
复制代码 |
|