简体   繁体   English

在 C++ 中比较数组是否相等

[英]Comparing arrays for equality in 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)

Here iar1 and iar2 are decaying to pointers to the first elements of the respective arrays.这里iar1iar2衰减到指向各自数组的第一个元素的指针。 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代替

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

}

Since nobody mentioned it yet, you can compare arrays with the std::equal algorithm:由于还没有人提到它,您可以将数组与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> .您需要包括<algorithm><iterator> If you don't use C++11 yet, you can write:如果你还没有使用 C++11,你可以这样写:

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

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

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

Nobody mentions memcmp ?没有人提到memcmp吗? This is also a good choice.这也是一个不错的选择。

/* 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/

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 eg equal(iar1, iar2) in your case, no need to pass the size of arrays.请注意,在调用时,我们只需要在您的情况下传递数组变量,例如equal(iar1, iar2) ,无需传递数组的大小。

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

Both store memory addresses to the first elements of two different arrays.两者都将内存地址存储到两个不同数组的第一个元素。 These addresses can't be equal hence the output.这些地址不能相等,因此输出。

If you are willing to use std::array instead of built-in arrays, you may use:如果您愿意使用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)

Right.正确的。 In most , if not all implementations of C, the array identifier can be implicitly casted to a pointer to the first element (ie the first element's address).大多数(如果不是所有的 C 实现)中,数组标识符可以隐式转换为指向第一个元素的指针(即第一个元素的地址)。 What you're doing here is comparing those addresses, which is obviously wrong.您在这里所做的是比较这些地址,这显然是错误的。

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.如果你在没有失败的情况下完成了两者,它们是平等的。

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.因此,这个条件if( iar1 == iar2 )实际上比较了两个地址。 Those pointers do not address the same object.这些指针不指向同一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM