【发布时间】:2016-03-18 08:00:36
【问题描述】:
#include <iostream>
using namespace std;
int main()
{
int *array1 = new int [5]();
int *array2 = new int [7]();
array1[2] = 3;// or anychange
array2[2] = 3;// to both arrays
if (array1==array2)
{
//if all values of the both arrays are equal
}
else
{
//if all values of the both arrays are not equal
}
return 0;
}
我有两个使用 new 动态分配的数组(大小可能相同也可能不同)。现在我想比较数组的所有元素(如果大小和元素相同,则为真,如果不是其中任何一个则为假)。
在 C++ 中怎么做? (对在我的问题场景中使用向量不感兴趣)
【问题讨论】:
-
那是不可能的——你丢失了每个数组的大小信息(尽管编译器在 new[]/delete[] 知道它)。
-
在这种情况下使用向量会更好。在您的场景中,您需要存储数组长度。然后您可以遍历数组(例如使用
for循环)。如果发现不等式,则将迭代器设置为 lenght 以完成循环(或使用 break),并将预先声明的 bool 设置为 false。在此之后检查布尔值。
标签: c++ compare dynamic-arrays