【问题标题】:C++ | Comparing two arrays using std::mismatch (or another STL alternative)C++ |使用 std::mismatch (或其他 STL 替代方案)比较两个数组
【发布时间】:2021-01-04 21:18:22
【问题描述】:

我面临比较两个 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++ 很陌生,所以我真的不知道这是什么意思。

【问题讨论】:

  • 这并没有解决问题,但是 10 个元素的数组的结束迭代器是 a + 10,而不是 a + 9。不过,更好的是使用std::begin(a)std::end(a)std::begin(b)。这样,如果您更改 a 中的元素数量,您仍然会得到正确的结束迭代器。

标签: c++ arrays stl mismatch


【解决方案1】:

std::mismatch() 返回一个 std::pair 的迭代器。在您的示例中,您使用的是 int* 类型的迭代器(int[] 数组 decays 指向指向其第一个元素的 int* 指针)。所以你需要将result 变量从pair&lt;int, int&gt; 更改为pair&lt;int*, int*&gt;。然后你需要在将它们的值打印到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;
}

【讨论】:

    【解决方案2】:

    std::mismatch 向容器返回一对迭代器,而不是一对ints。在这种情况下,由于您有一个数组,因此迭代器类型为int*

    简单的解决方法是在调用时推断类型:

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

    从 c++17 开始,您也可以命名该对的各个元素:

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

    【讨论】:

      猜你喜欢
      • 2011-07-24
      • 1970-01-01
      • 2020-02-20
      • 2010-09-10
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 2010-11-07
      • 2020-05-29
      相关资源
      最近更新 更多