0

I am little puzzled, here is what I did

  1. First vector named vec has 5 elements
  2. Second vector named s has 3 elements.
  3. Two elements are common to them
  4. 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.

mtk
  • 13,221
  • 16
  • 72
  • 112

1 Answers1

0

Maybe it's because you forgot to replace v on vec_out at the end of your code. This code works right (14 42):

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()); >*/
vec_out.resize(itr - vec_out.begin());                                      

cout<<"intersection\n";                                                     
for(itr = vec_out.begin(); itr != vec_out.end(); itr++)                     
      cout << " " << *itr;  
Yury
  • 116
  • 6