用C比较平等阵列++ [英] Comparing arrays for equality in C++

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

问题描述

可有人请,为什么从以下code的输出是说,数组的不等于

给我解释一下

  INT的main()
{    INT IAR1 [] = {1,2,3,4,5};
    INT iar2 [] = {1,2,3,4,5};    如果(IAR1 == iar2)
        COUT<< 数组是平等的。
    其他
        COUT<< 数组是不相等的。    返回0;
}


解决方案

 如果(IAR1 == iar2)

下面 IAR1 iar2 腐烂的访问指向的第一要素相应的阵列。因为它们是两个不同的阵列,指针值是,当然,不同的和你的对比测试不相等。

要做到各个元素的比较,您必须写一个循环;或者使用的std ::阵列而不是

 的std ::阵列< INT,5个IAR1 {1,2,3,4,5};
的std ::阵列< INT,5个iar2 {1,2,3,4,5};如果(IAR1 == iar2){
  //数组内容是相同的}其他{
  // 不一样}

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)

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.

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天全站免登陆