在c++中,如何检查一个数组的元素是否也是另一个数组中的元素
How to check if an element of one array is also element of another in c++?
我需要编写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;
}
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int