Vamsi Mohan
Vamsi Mohan

Reputation: 41

Why is std::set_intersection not working?

I have the following code:

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

int main() {
// your code goes here
int t;
cin>>t;
while(t--)
{
    string a;
    string b;
    cin>>a;
    cin>>b;
    vector<char> v1(a.begin(),a.end());
    vector<char> v2(b.begin(),b.end());

    sort(v1.begin(),v1.end());
    sort(v2.begin(),v2.end());
    vector<char> c;
    auto ls = set_intersection(v1.begin(),v1.end(),v2.begin(),v2.end(),c.begin());
    cout<<"hello"<<endl;
    cout<<ls-c.begin()<<endl;
    cout<<c.size()<<endl;

}
return 0;
}

Nothing is printed after the set_intersection line, not even "hello" which has no relation to the intersection line, why??

Upvotes: 1

Views: 1149

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409452

It doesn't work because c is empty. This means that c.begin() be equal to c.end(), and dereferencing an end iterator leads to undefined behavior.

You need to insert the elements in the vector, for example by using std::back_inserter:

auto ls = set_intersection(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(c));

There's one problem with this though: The iterator that set_intersection will return is the end of the back_inserter iterator you passed to the set_intersection function. That iterator is not related to c.begin() which means you can't really do ls - c.begin().

Unfortunately there's really no way to get the distance between the initial back_inserter(c) iterator and ls.

Upvotes: 6

Related Questions