我有两组int:A = {1,3,5,7}
和B = {2,4,5,7}
。如何将它们相交并将结果保存在集合A中?所以我希望A在操作后等于{5,7}
。
答案 0 :(得分:2)
std::vector<int> A{1,3,5,7};
std::vector<int> B{2,4,5,7};
// Sort
std::sort(A.begin(), A.end());
std::sort(B.begin(), B.end());
std::vector<int> result;
std::set_intersection(A.begin(), A.end(),
B.begin(), B.end(),
std::back_inserter( result ));
答案 1 :(得分:0)
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> v1{1,2,3,4,5,6,7,8};
std::vector<int> v2{ 5, 7, 9,10};
// Precondition: make sure they're sorted
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 << ' '; // 5 7
}