使用 set_intersection 进行动态分配?

Using set_intersection with dynamic allocation?

我正在阅读有关 set_intersection 的文章,它似乎期望用户提前分配正确数量的 space(或更多),但这不是很奇怪吗?在 C++ 中,您经常使用 std::vector 动态分配 space 。为什么 set_intersection 隐含地要求提前分配 space,而根据结果数据大小(动态)分配显然更有效?是否希望在事先知道交集大小的情况下最大化性能?交集大小未知的常见情况如何?

有没有"magical way"直接为每个添加到vector的元素分配一个slot?

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

不,不是(除非我误解了你的问题):

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