解决方法很简单,我就不详细解释了。
我展示了 3 种不同的实现。请注意,最后一个是单衬。
请看:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
std::vector<int> v1{ 1,2,3,4,5,6,7,8,9,10 };
std::vector<int> v2{ 2,4,6,8,10 };
int main() {
// Solution 1
std::cout << "\nSolution 1. Values that are in v1 and v2\n";
// Simple solution
for (const int i : v1)
for (const int j : v2)
if (i == j) std::cout << i << "\n";
// Solution 2: The C++ solution
std::cout << "\n\nSolution 2. Values that are in v1 and v2\n";
// If you want to store the result
std::vector<int> result{};
// After this, result contains values that are both in v1 and v2
set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(result));
// Debug output
std::copy(result.begin(), result.end(), std::ostream_iterator<int>(std::cout, "\n"));
// Solution 3: The C++ all in one solution
std::cout << "\n\nSolution 3. Values that are in v1 and v2\n";
// One-liner
set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}