如何检查两个数组是否相同

时间:2019-05-16 01:55:54

标签: c++

我需要检查两个数组是否相同或不同。 testScores是二维的,而answerKey是一维的。

我试图这样做:

if (testScores[student][20] != answerKey[0]){
  cout<<"Right
  cout<<endl;
} else {
  cout<<"Not working";
  cout<<endl;
}

但仍然不起作用

if (testScores == answerKey){
  sum +=1;
  cout<<"Sum: "<<sum;
} else if (testScores != answerKey) {
  sum -= 1;
  cout<<"Sum: "<<sum;
} else(testScores = ' ')
  sum += 0;
cout<<"Sum: "<<sum;
}

1 个答案:

答案 0 :(得分:1)

  

如何检查两个数组是否相同

您可以使用std::equal。这就是该功能的目的,目的是测试两个范围(在您的情况下为数组)是否相同或不同。

在此示例仅使用一名学生,但是使用两个答案键,每个答案键只有5个答案。请扩展此范围以适应实际的学生人数和答案。

#include <algorithm>
#include <iostream>

int main()
{
   const int numStudents = 1;
   const int numScores = 5;
   int testScores[numStudents][numScores] = {{10,20,30,40,50}};
   int answerKey[] = {10,20,30,40,50};
   int answerKey2[] = {10,20,30,40,60};

   for (int i = 0; i < numStudents; ++i)
   {
      if (std::equal(&testScores[i][0], 
                     &testScores[i][numScores + 1], answerKey))
         std::cout << "Student has all right answers for key 1\n";
      else
         std::cout << "Student does not have all right answers for key 1\n";
   }

   for (int i = 0; i < numStudents; ++i)
   {
      if (std::equal(&testScores[i][0], 
                     &testScores[i][numScores + 1], answerKey2))
         std::cout << "Student has all right answers for key 2\n";
      else
         std::cout << "Student does not have all right answers for key 2\n";
   }
}

输出:

Student has all right answers for key 1
Student does not have all right answers for key 2