I am little puzzled, here is what I did
- First vector named
vec
has 5 elements - Second vector named
s
has 3 elements. - Two elements are common to them
- Did a union of them, Got correct output. Result was stored in
vec_out
Problem begins --
5. Did a intersection of them and stored in vec_out
, gives no result, i.e. nothing intersects
6. Changed the result to be written to a brand new vector v
, shows correct result i.e. 2 elements intersect
So, I would like to know, why didn't the reuse of vec_out
work for finding out set_intersection
(it's the 5th argument to set_intersection) ?
Any hints? Here is the code
vector<int> vec(5);
vector<int> s(3);
vector<int> vec_out(10);
vector<int>::iterator itr;
vec[0]=3;
vec[1]=4;
vec[2]=4;
vec[3]=14;
vec[4]=42;
s[0]=14;
s[1]=42;
s[2]=442;
set_union(vec.begin(), vec.end(), s.begin(), s.end(), vec_out.begin());
cout<<"union\n";
for(itr = vec_out.begin(); itr != vec_out.end(); itr++)
cout << " " << *itr;
cout<<endl;
std::vector<int> v(10); // Using a new vector works fine, and gives result
// THIS BELOW LINE IS NOT WORKING
//itr=set_intersection(vec.begin(), vec.end(), s.begin(), s.end(), vec_out.begin());
itr=set_intersection(vec.begin(), vec.end(), s.begin(), s.end(), v.begin());
v.resize(itr - v.begin());
cout<<"intersection\n";
for(itr = v.begin(); itr != v.end(); itr++)
cout << " " << *itr;
FYI: I am correctly iterating over the expected vector, no issue with display i.e. I was iterating over vec_out when I tried step 5.