后端 如何求两个集合的差集、删除两矢量中相同元素?

dusongzi · August 22, 2021 · 0 hits
#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 用法与范例

No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.