问题描述
我面临着比较两个int
数据类型的c ++数组的任务。我特别不能使用自己的任何循环(for
,while
),并被鼓励使用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);