-8

Here in the below code i have 4 vectors a,b,v1,v2.

After calculating set difference of a and b, b and a I have stored the reuslts of them in v1 and v2 vectors respectively.

  • vector 'a' has the elements {'a','b','c'} and
  • vector 'b' has the elements {'a','b'}.
  • Now v1 contains 'c' with its size 1 but v2 contains none and with size 1. How is this possible? Note that vectors a and b contains the elements of a set!!!

Here is my code:

    #include <bits/stdc++.h>
    #define REP(i,x,y) for(auto i=x;i!=y;i++)
    using namespace std;
    int t;
    string s1,s2;
    bool flag;
    int main() 
    {
    cin>>t;
    while(t--)
    {
    flag=false;
    set<char> a,b;  multiset<char> A,B;
    cin>>s1>>s2;
    REP(i,0,s1.length())
    {
        A.insert(s1[i]);
        a.insert(s1[i]);
        B.insert(s2[i]);
        b.insert(s2[i]);
    }
    vector<char> v1,v2;
  set_difference(a.begin(),a.end(),b.begin(),b.end(),inserter(v1,v1.begin()));
    set_difference(b.begin(),b.end(),a.begin(),a.end(),inserter(v2,v2.begin()));
    cout<<v1.size()<<" "<<v2.size()<<"\n";
    REP(i,v1.begin(),v1.end())
    cout<<*i<<" ";
    cout<<"\n";
    REP(i,v2.begin(),v2.end())
    cout<<*i<<" ";
    cout<<"\n";
}
return 0;

}

Input: 3 abaac ab aba cde ab cd

Output:

    1 1
    c 

    2 3
    a b 
    c d e 
    2 2
    a b 
    c d 

2 Answers2

1

set_difference expects sorted containers.

template <class InputIterator1, class InputIterator2, class OutputIterator>
  OutputIterator set_difference (InputIterator1 first1, InputIterator1 last1,
                                 InputIterator2 first2, InputIterator2 last2,
                                 OutputIterator result);

Constructs a sorted range beginning in the location pointed by result with the set difference of the sorted range [first1,last1) with respect to the sorted range [first2,last2).


vector<int> a={'a','b','a','c'}, b ={'a','b'}, v1,v2;

std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());

set_difference(a.begin(),a.end(),b.begin(),b.end(),inserter(v1,v1.begin()));
set_difference(b.begin(),b.end(),a.begin(),a.end(),inserter(v2,v2.begin()));


std::cout << "Vector v1: (" << v1.size() << ")" << std::endl;
for(auto it:v1)
{
    std::cout << it << std::endl;
}

std::cout << "Vector v2: (" << v2.size() << ")" << std::endl;
for(auto it:v2)
{
    std::cout << it << std::endl;
}

Output

Vector v1: (2)
97
99
Vector v2: (0)
kocica
  • 6,412
  • 2
  • 14
  • 35
-1

There is no such a possibility as far as I know. The problem is with code itself!! There while giving input I'm supposed to give the strings as equal sized strings. That's where I went wrong and thereby I have inserted nothing into the set. Thank you everyone for having you precious time solving my problem.