【问题标题】:How to check if an element of one array is also element of another in c++?如何检查一个数组的元素是否也是c ++中另一个数组的元素?
【发布时间】:2019-11-10 15:25:14
【问题描述】:

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

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

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

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

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

【问题讨论】:

标签: c++ arrays for-loop


【解决方案1】:

解决方法很简单,我就不详细解释了。

我展示了 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;
}

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 2017-02-10
    • 2020-06-13
    • 2021-12-03
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    相关资源
    最近更新 更多