2015-10-07 35 views
0

我在阅读有关set_intersection,它似乎预计用户提前分配正确的空间量(或更多),但并不奇怪?在C++中,您经常使用std::vector,它在旅途中动态分配空间。为什么set_intersection隐式需要预先分配空间,因为根据结果数据大小(动态地)分配明显更有效?交通规模预先已知时,是否希望最大限度提高性能?交叉点大小未知的常见情况如何?使用set_intersection进行动态分配?

是否有任何“神奇的方式”直接分配每个元素添加到矢量一个插槽?

+0

我想实际的问题是'什么是OutputIterator,我如何使用set_intersection'。 – pmr

+0

@pmr 是的,我知道'OutputIterator'是这个解决方案中有意义的项目。我会说这个问题指向这个问题,但不需要知道'OutputIterator'的特定性。 – zehelvion

回答

3

,它似乎希望用户预先分配的空间(或更多)的正确量

不,不(除非我误解你问):

#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 << ","; 
} 
+0

谢谢!非常有用:D'back_inserter'就是所需要的。 – zehelvion