C ++ |使用std :: mismatch比较两个数组或另一个STL替代方案

问题描述

我面临着比较两个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,b);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...