Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

can anyone help me with a c++ program for symmetric difference of two sets using loops

0 votes
asked Jul 14, 2020 by Prachi Jain (120 points)

2 Answers

0 votes
answered Jul 15, 2020 by xDELLx (6,200 points)
//used c++17 compiler

#include <iostream>
#include <set>

using namespace std;
int main()
{
    //printf("Hello World");
    //Sym diff of s1 ,s2 = (s1 ᴜ s2) - (s1  s2)
    //ie all elements from s1 , s2 excluding common elements in s1 ,s2
    set<int> s1 = {1,2,3,4,5,10,11,12,13};
    //set<int> s2 = {1,2,3,4,5,10,11,12,13};
   set<int> s2 = {3,4,6,7,8,9};
    set<int> s3;
    //add logic to enter user input elements if needed
    
    //find elements from s1 in s2 ,
    //if present delete them from s1,s2
    //if no present ad d to new set
    //copy elemts remaing from s2 ,if any to new set
    
    for (auto it =s1.begin();it!=s1.end();){
        auto it2 = s2.find(*it) ;
        if ( it2 == s2.end()){
            s3.emplace(*it);
            it++;
        }
        else{
            it = s1.erase(it);
            //it =s1.begin(); //erasing an element invalidates the iterator
            s2.erase(it2);
        }
    }
    
    for (auto& e : s2){
        s3.emplace(e);
    }
    
    if (s3.empty() == true){
       std::cout << "Empty sym diff set \n";
    }else{
        std::cout << "sym diff set :\n";
        for ( auto& x:s3){
            cout << x <<" ";
        }
    }
    cout<<endl;
    return 0;
}
0 votes
answered Jul 16, 2020 by Peter Minarik (15,580 points)

The c++ library already has a solution for this problem: http://www.cplusplus.com/reference/algorithm/set_symmetric_difference/

You can also check there what a possible implementation could be for symmetric difference.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...