在 C++ 中比较数组的相等性 [英] Comparing arrays for equality in C++

查看:32
本文介绍了在 C++ 中比较数组的相等性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释为什么以下代码的输出说数组不相等?

Can someone please explain to me why the output from the following code is saying that arrays are not equal?

int main()
{

    int iar1[] = {1,2,3,4,5};
    int iar2[] = {1,2,3,4,5};

    if (iar1 == iar2)
        cout << "Arrays are equal.";
    else
        cout << "Arrays are not equal.";

    return 0;   
}

推荐答案

if (iar1 == iar2)

这里的 iar1iar2 正在衰减指向各自数组的第一个元素的指针.由于它们是两个不同的数组,因此指针值当然不同并且您的比较测试不相等.

Here iar1 and iar2 are decaying to pointers to the first elements of the respective arrays. Since they are two distinct arrays, the pointer values are, of course, different and your comparison tests not equal.

要进行逐元素比较,您必须编写一个循环;或使用 std::array 代替

To do an element-wise comparison, you must either write a loop; or use std::array instead

std::array<int, 5> iar1 {1,2,3,4,5};
std::array<int, 5> iar2 {1,2,3,4,5};

if( iar1 == iar2 ) {
  // arrays contents are the same

} else {
  // not the same

}

这篇关于在 C++ 中比较数组的相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆