关于集合问题
例如集合a集合 b求b在a中的余集集合a 1 2 3 4 5 6
集合b 2 4 5 6 7 8
输出 1 3 #include <iostream>
#include <vector>
const std::vector<int> complement(const std::vector<int> &a, const std::vector<int> &b)
{
std::vector<int> res;
for(const auto i: a)
{
bool flag = true;
for(const auto j: b)
{
if(i == j)
{
flag = false;
break;
}
}
if(flag)
res.push_back(i);
}
return res;
}
std::ostream &operator<<(std::ostream &os, const std::vector<int> &data)
{
for(const auto i: data)
{
std::cout << i << " ";
}
return os;
}
int main()
{
std::vector<int> a = {1, 2, 3, 4, 5, 6};
std::vector<int> b = {2, 4, 5, 6, 7, 8};
std::cout << complement(a, b) << std::endl;
return 0;
}
a =
b =
for i in a:
if i not in b:
print(i,end=" ")
楼上写的太高深看不到{:5_90:} 荣耀 发表于 2019-12-21 15:33
a =
b =
for i in a:
这里是C/C++,不是py
提供一个排序之后的算法,效率要高一些:#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");
}
页:
[1]