![](/img/trans.png)
[英]How do I compare two arrays with different lengths as efficiently as possible?
[英]How do I check if two arrays are the same or different
我需要檢查兩個數組是否相同或不同。 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;
}
如何檢查兩個數組是否相同或不同
您可以使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.