簡體   English   中英

如何在 c++ 中檢查一個數組的元素是否也是另一個數組的元素?

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

我需要編寫 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 關鍵字 先感謝您。

解決方案非常簡單,我不會解釋細節。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM