在c++中,如何检查一个数组的元素是否也是另一个数组中的元素

How to check if an element of one array is also element of another in c++?

本文关键字:数组 元素 c++ 是否 另一个 一个 检查 何检查      更新时间:2023-10-16

我需要编写c++代码来解决家庭作业。该代码的一部分应该用于循环,该循环将检查一个数组的元素是否也是另一个的一部分

我试图通过嵌套的for循环、if-else-if-else条件等来实现这一点。我也用Python 3编写了代码,但我需要用c++编写。

这是Python中的代码,可以解决这个问题:

for x in array:
if m in array2:
print m
break

这段代码将如何翻译成c++?Python关键字的c++版本是什么(如果存在(?提前谢谢。

解决方案非常简单,我不解释细节。

我展示了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 v2n";
// 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 << "nnSolution 2. Values that are in v1 and v2n";
// 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 << "nnSolution 3. Values that are in v1 and v2n";
// One-liner
set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, "n"));
return 0;
}