0

I'm reading about set_intersection and it appears to expect the user to allocate the correct amount of space (or more) in advance but isn't that strange? In c++ you often use std::vector which dynamically allocates space on the go. Why would set_intersection implicitly require allocation of space in advance when it is clearly more effective to allocate based on the resulting data size (dynamically)? Is it in hope to maximize performance when the intersection size is known in advance? What about the common case where there intersection size is not known?

Is there any "magical way" to directly allocate one slot per element added to the vector?

Yogeshree Koyani
  • 1,649
  • 10
  • 19
AturSams
  • 7,568
  • 18
  • 64
  • 98
  • I guess the actual question is `What is an OutputIterator and how do I use one with set_intersection`. – pmr Oct 07 '15 at 14:01
  • @pmr Yes, had I know the `OutputIterator` is the meaningful item in this solution. I'd say the question points towards that question but without requiring the specifity of knowing of an `OutputIterator` to begin with. – AturSams Oct 07 '15 at 14:02

1 Answers1

4

and it appears to expect the user to allocate the correct amount of space (or more) in advance

No, it doesn't (unless I misunderstood what you're asking):

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
    //vectors to intersect
    std::vector<int> first{1,2,4,3,8,6,7,5};
    std::vector<int> second{3,15,4,16,36};
    //they need to be sorted 
    std::sort(first.begin(), first.end()); //{1,2,3,4,5,6,7,8}
    std::sort(second.begin(), second.end()); //{3,4,15,16,36}

    //intersection result
    std::vector<int> intersection;

    //intersecting
    std::set_intersection(first.begin(), first.end(),
                          second.begin(), second.end(),
                          std::back_inserter(intersection));

    //output: 3,4
    for(int n : intersection)
        std::cout << n << ",";
}
SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105