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

answered Jul 15, 2020 by (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;
}