在 C++ 中比较数组的相等性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12866413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:42:05  来源:igfitidea点击:

Comparing arrays for equality in C++

c++arrayscomparisonequality

提问by vladinkoc

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;   
}

回答by Praetorian

if (iar1 == iar2)

Here iar1and iar2are decayingto 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.

这里iar1iar2衰减的指针到相应的阵列的第一个元素。由于它们是两个不同的数组,因此指针值当然不同并且您的比较测试不相等。

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

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

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

}

回答by InstallingXubuntuRightNow

Since nobody mentioned it yet, you can compare arrays with the std::equalalgorithm:

由于还没有人提到它,您可以将数组与std::equal算法进行比较:

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

if (std::equal(std::begin(iar1), std::end(iar1), std::begin(iar2)))
    cout << "Arrays are equal.";
else
    cout << "Arrays are not equal.";

You need to include <algorithm>and <iterator>. If you don't use C++11 yet, you can write:

您需要包括<algorithm><iterator>。如果你还没有使用 C++11,你可以这样写:

if (std::equal(iar1, iar1 + sizeof iar1 / sizeof *iar1, iar2))

回答by Fred Larson

You're not comparing the contents of the arrays, you're comparing the addresses of the arrays. Since they're two separate arrays, they have different addresses.

您不是在比较数组的内容,而是在比较数组的地址。由于它们是两个独立的数组,因此它们具有不同的地址。

Avoid this problem by using higher-level containers, such as std::vector, std::deque, or std::array.

通过使用更高级别的容器,如避免这个问题std::vectorstd::dequestd::array

回答by Paul S.

Array is not a primitive type, and the arrays belong to different addressesin the C++ memory.

数组不是原始类型,数组在C++内存中属于不同的地址

回答by Saurav Sahu

If you are reluctant to change your existing code to std::array, then use a couple of methods instead which takes non-type template arguments:

如果您不愿意将现有代码更改为std::array,则使用一些方法来代替,它们采用非类型模板参数

//Passed arrays store different data types
template <typename T, typename U, int size1, int size2>
bool equal(T (&arr1)[size1], U (&arr2)[size2] ){
    return false;
}

//Passed arrays store SAME data types
template <typename T, int size1, int size2>
bool equal(T (&arr1)[size1], T (&arr2)[size2] ){
    if(size1 == size2) {
        for(int i = 0 ; i < size1; ++i){
            if(arr1[i] != arr2[i]) return false;
        }
        return true;
    }
    return false;
}

Here is the demo. Note that, while calling, we just need to pass the array variables e.g. equal(iar1, iar2)in your case, no need to pass the size of arrays.

这是演示。请注意,在调用时,我们只需要传递数组变量,例如equal(iar1, iar2)在您的情况下,不需要传递数组的大小。

回答by Xiangyi Meng

Nobody mentions memcmp? This is also a good choice.

没人提memcmp?这也是一个不错的选择。

/* memcmp example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char buffer1[] = "DWgaOtP12df0";
  char buffer2[] = "DWGAOTP12DF0";

  int n;

  n=memcmp ( buffer1, buffer2, sizeof(buffer1) );

  if (n>0) printf ("'%s' is greater than '%s'.\n",buffer1,buffer2);
  else if (n<0) printf ("'%s' is less than '%s'.\n",buffer1,buffer2);
  else printf ("'%s' is the same as '%s'.\n",buffer1,buffer2);

  return 0;
}

Ref: http://www.cplusplus.com/reference/cstring/memcmp/

参考:http: //www.cplusplus.com/reference/cstring/memcmp/

回答by Vachaspati Mishra

Both store memory addresses to the first elements of two different arrays. These addresses can't be equal hence the output.

两者都将内存地址存储到两个不同数组的第一个元素。这些地址不能相等,因此输出。

回答by Rahul Tripathi

You are comparing the addresses instead of the values.

您正在比较地址而不是值。

回答by vladinkoc

When we use an array, we are really using a pointer to the first element in the array. Hence, this condition if( iar1 == iar2 )actually compares two addresses. Those pointers do not address the same object.

当我们使用数组时,我们实际上是在使用指向数组中第一个元素的指针。因此,此条件if( iar1 == iar2 )实际上是比较两个地址。这些指针不指向同一个对象。

回答by slugonamission

Right. In most, if not all implementations of C, the array identifier can be implicitly casted to a pointer to the first element (i.e. the first element's address). What you're doing here is comparing those addresses, which is obviously wrong.

对。在大多数(如果不是所有的)C 实现中,数组标识符可以隐式转换为指向第一个元素(即第一个元素的地址)的指针。你在这里做的是比较这些地址,这显然是错误的。

Instead, you need to iterate over both arrays, checking each element against each other. If you get to the end of both without a failure, they're equal.

相反,您需要遍历两个数组,相互检查每个元素。如果你在没有失败的情况下完成了两者,那么它们是平等的。