#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void)
{
int n1,n2,x,y;
vector<int>a,b,d,e;
struct data
{
vector<int>a;
vector<int>b;
};
cin>>n1;
for(int i=0;i<n1;i++)
{
cin>>x;
a.push_back(x);
}
sort(a.begin(),a.end());
cin>>n2;
for(int i=0;i<n2;i++)
{
cin>>y;
b.push_back(y);
}
sort(b.begin(),b.end());
for(int i=0;i<a.size();i++)
{
for(int j=0;j<b.size();j++)
{
e.push_back(a[i]);
if(a[i]==b[j])
a.erase(a.begin()+i);
}
}
sort(e.begin(),e.end());
cout<<"{";
for(int i=0;i<e.size();i++)
{
cout << e[i] << ",";
}
cout<<"\b}";
cout <<"\n";
return 0;
}
集合就用 std::set 來處理比較方便
#include <iostream>
#include <set>
using namespace std;
void inputSet(set<int> &s)
{
int n, x;
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> x;
s.insert(x);
}
}
int main(void)
{
set<int> a, b, c;
inputSet(a);
inputSet(b);
for (set<int>::iterator it = a.begin(); it != a.end(); ++it)
{
if (b.count(*it) == 0)
{
c.insert(*it);
}
}
cout << '{';
for (set<int>::iterator it = c.begin(); it != c.end(); ++it)
{
cout << *it << ',';
}
cout << "\b}\n";
return 0;
}
參考資料:C++ std::set 用法與範例