I am faced with the task of comparing two c++ arrays that are of int
data type. I specifically cannot use any loops (for
, while
) of my own, and was encouraged to use an STL function. I found std::mismatch()
and it seems to be what I want, but I am unable to get it working with a basic array.
Here is my code:
#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;
}
I am getting the following error:
error: conversion from 'std::pair' to non-scalar type 'std::pair' requested
I am pretty new to C++, so I don't really know what this means.
std::mismatch
returns a pair of iterators to the container, not a pair of int
s. In this case, since you have an array, the iterator type is int*
.
The simple solution is to deduce the type when calling it instead:
auto result = std::mismatch(a, a + 9, b);
From c++17, you can name the individual elements of the pair as well:
auto [i, j] = std::mismatch(a, a + 9, b);