簡體   English   中英

C++ | 使用 std::mismatch(或其他 STL 替代方案)比較兩個數組

[英]C++ | Comparing two arrays using std::mismatch (or another STL alternative)

我面臨着比較兩個int數據類型的 C++ 數組的任務。 我特別不能使用我自己的任何循環( forwhile ),並被鼓勵使用 STL 函數。 我找到了std::mismatch() ,它似乎是我想要的,但我無法讓它與基本數組一起工作。

這是我的代碼:

#include <iostream>     // cout
#include <algorithm>    // std::mismatch
#include <utility>      // pair

int main()
{
    int a[10] = {1,3,5,7,9,11,13,15,17,19};
    int b[10] = {2,4,6,8,10,12,14,16,18,20};

    std::pair<int, int> result = 
        std::mismatch(a, a + 9, b);
    
    std::cout<<result.first<<" "<<result.second<<std::endl;

    return 0;
}

我收到以下錯誤:

錯誤:請求從“std::pair”轉換為非標量類型“std::pair”

我對 C++ 很陌生,所以我真的不知道這意味着什么。

std::mismatch()返回一個std::pair迭代器。 在您的示例中,您使用的是int*類型的迭代器(一個int[]數組衰減為指向其第一個元素的int*指針)。 因此,您需要將result變量從pair<int, int>更改為pair<int*, int*> 然后您需要在將它們的值打印到cout時取消引用這些迭代器,例如:

#include <iostream>     // cout
#include <algorithm>    // std::mismatch
#include <utility>      // pair

int main()
{
    int a[10] = {1,3,5,7,9,11,13,15,17,19};
    int b[10] = {2,4,6,8,10,12,14,16,18,20};

    int *a_end = a + 10;
    std::pair<int*, int*> result = std::mismatch(a, a_end, b);

    if (result.first != a_end)
        std::cout << *(result.first) << " " << *(result.second) << std::endl;
    else
        std::cout << "no mismatch found" << std::endl;

    return 0;
}

std::mismatch向容器返回一對迭代器,而不是一對int 在這種情況下,由於您有一個數組,因此迭代器類型為int*

簡單的解決方案是在調用它時推斷類型:

auto result = std::mismatch(a, a + 9, b);

從 c++17 開始,您也可以命名該對的各個元素:

auto [i, j] = std::mismatch(a, a + 9, b);

暫無
暫無

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

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