micheal reid
micheal reid

Reputation: 1

How do I check if two arrays are the same or different

I need to check to see if both my arrays are the same or different. testScores is two dimensional and answerKey is one dimensional.

I've tried to do this:

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

but still doesn't work

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

Upvotes: 0

Views: 94

Answers (1)

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

How do I check if two arrays are the same or different

You can use std::equal. That's the purpose of that function, to test if two ranges (in your case, arrays) are the same or different.

Here is an example using just one student, but two answer keys with only 5 answers each. Please expand this to accommodate the actual number of students and answers.

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

Output:

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

Upvotes: 1

Related Questions