c++ - 严格相同的数组输入

标签 c++ arrays boolean

有什么清理这段代码的一般技巧吗? 似乎我可以完成任务而无需进行所有检查..

谢谢!

txt书的问题: (严格相同的数组)如果两个数组 list1[] 和 list2[] 具有相同的长度并且 list1[] 对每个 [i] 等于 list2[],则它们严格相同。

使用以下 header 编写一个函数,如果 list1 和 list2 完全相同则返回 true

  bool strictlyEqual(const int list1[], const int list2[], int size)

编写一个测试程序,提示用户输入两个整数列表,并显示这两个列表是否完全相同。示例运行如下。请注意,输入中的第一个数字表示列表中元素的数量。此号码不在列表中。假设列表大小是最大的

我的代码:

   #include <iostream>
   using namespace std;

   bool strictlyEqual(int const list1[], int const list2[], int size);

   bool strictlyEqual (int x1[], int x2[], int n)
   {
     int f=0; int i;
     for (i =1; i<=n; i++)
     {
               if (x1[i] != x2[])
               {
                  // breaks loop
                    f=1;
                    break;
                }
     } 

 if (f==0)
 return (true);
 else 
 return(false);
 }


int main ()
cout << "enter list1: " << endl;
int list1[20], i;
cin >> list1[0];
for (i=1; i<= list1[0]; i++)
cin>> list1[i];

cout <<"enter the list2" << endl;
int list2[20];
cin >> list2[0];
for (i=1; i<= list2[0]; i++)
cin >> list2[i];

if (list1[0] == list2[0]
{
     int size = list2[0];
     bool v=strictlyEqual(list1, list2, size);
     if (v== true)
     cout << "identical" << endl;
     else 
     cout << "not identical " << endl;
 }

  return 0;
 }

最佳答案

一个简单的解决方案是使用 memcmp功能。

int memcmp ( const void * ptr1, const void * ptr2, size_t num );

Compares the first num bytes of the block of memory pointed by ptr1 to the first num bytes pointed by ptr2, returning zero if they all match or a value different from zero representing which is greater if they do not.

bool strictlyEqual (int x1[], int x2[], int n){
    return memcmp(x1, x2, n * sizeof(int)) == 0;
}

关于c++ - 严格相同的数组输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40967983/

相关文章:

c++ - 内部类和初始化

c++ - 组合整数和 float : performance considerations

c++ - 如何使用 std::max 或 std::min 作为函数参数

php - 如何获取 php/laravel 数组中元素的位置

android - 您可以在其他应用程序中使用一个应用程序中的 .so 库吗?

java - 计算具有重复项的数组列表中每个不同数组的出现次数

javascript - 如何使用 Javascript 对对象中的年份进行分组?

java - 我的 for 循环出了什么问题?

php - 在 php 中打印 false

c++ - 类成员函数的模板特化,以便不在 bool 上使用增量运算符