2

I have a class which has two attributes :

 set< int > ens1_;
 set< int > ens2_;

Now, I have a method which finds the intersection between these two sets. Here is what I wrote in my method:

set< int > ens;
set< int >::iterator it;

it = set_intersection(ensEntier1_.begin(), ensEntier1_.end(), ensEntier2_.begin(), ensEntier2_.end(), ens.begin());
return ens;

It gives me an error at compile inside the stl_algo.h but I don't know from where to start to correct the error

Thank you for your time

Etienne

Etienne Noël
  • 5,988
  • 6
  • 48
  • 75

3 Answers3

1

It looks like you need to use something like an insert_iterator for your result.

It's also unclear how the ensEntier1_ and ensEntier2_ you're passing to set_intersection correspond to ens1_ and ens2_, but for the moment I'll assume they do.

Edit: here's a working example:

#include <algorithm>
#include <set>
#include <iterator>
#include <iostream>

int main(){ 

    std::set<int> set1;
    std::set<int> set2;

    set1.insert(1);
    set1.insert(2);
    set1.insert(5);

    set2.insert(2);
    set2.insert(3);
    set2.insert(5);

    std::set<int> result;

    std::set_intersection(set1.begin(), set1.end(), 
                          set2.begin(), set2.end(), 
                          std::inserter(result, result.end()));
    std::copy(result.begin(), result.end(), 
              std::ostream_iterator<int>(std::cout, "\n"));
    return 0;
}
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
1

The 5th argument to the set_intersection overload you're calling expects an output iterator; ens.begin() does not return an output iterator. Try this instead:

set<int> ens;
set_intersection(
    ens1_.begin(),
    ens1_.end(),
    ens2_.begin(),
    ens2_.end(),
    inserter(ens, ens.end())
);
return ens;

Note: make sure you #include <iterator>.

ildjarn
  • 62,044
  • 9
  • 127
  • 211
0

set_intersection must write to a sequence container such as vector, not an associative container such as set, if the container's native iterators are used.

Try this:

vector< int > ens( min( ensEntier1_.size(), ensEntier2_.size() );
vector< int >::iterator it;

it = set_intersection(ensEntier1_.begin(), ensEntier1_.end(), ensEntier2_.begin(), ensEntier2_.end(), ens.begin());
ens.erase( it, ens.end() );
return ens;
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
  • Why would it need a sequence? It appears to require only an output iterator. – Jerry Coffin Apr 03 '11 at 03:06
  • @Jerry: Right. I'll let you cover the insert_iterator alternative… personally I tend to use `vector` and `sort` for this kind of thing… – Potatoswatter Apr 03 '11 at 03:09
  • Using vector and sort is fine (in fact, quite possibly superior). You still need to either use a back_inserter, or (as you've done above) allocate enough space for the result ahead of time. – Jerry Coffin Apr 03 '11 at 03:15