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

0 votes
asked Jul 14 by PB_44_Prachi Jain (120 points)

2 Answers

0 votes
answered Jul 15 by xDELLx (2,430 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()){
            it = s1.erase(it);
            //it =s1.begin(); //erasing an element invalidates the iterator
    for (auto& e : s2){
    if (s3.empty() == true){
       std::cout << "Empty sym diff set \n";
        std::cout << "sym diff set :\n";
        for ( auto& x:s3){
            cout << x <<" ";
    return 0;
0 votes
answered Jul 16 by Peter Minarik (7,160 points)

The c++ library already has a solution for this problem:

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.