Str*_*ker 2 c++ algorithm stl set set-intersection
从包含来自两个集合的值的 2 个集合创建子集的最有效方法是什么?任何 C++ STL 库都可以用来解决这个问题(如果可能的话,不用 Boost 库):
Set A = {2, 3, 5, 7, 11, ...}
Set B = {1, 3, 5, 7, 9, 11, ...}
Subset should be = {3, 5, 7, 11, ...}
Run Code Online (Sandbox Code Playgroud)
您可以通过使用来做到这一点set_intersection,您会在那里找到如何使用它的示例:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> v1{2, 3, 5, 7, 11};;
std::vector<int> v2{1, 3, 5, 7, 9, 11};
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::vector<int> v_intersection;
std::set_intersection(v1.begin(), v1.end(),
v2.begin(), v2.end(),
std::back_inserter(v_intersection));
for(int n : v_intersection)
std::cout << n << ' ';
}
Run Code Online (Sandbox Code Playgroud)
结果将是:
3 5 7 11
Run Code Online (Sandbox Code Playgroud)