如何检查数组中的值

How to check for a value in an array

本文关键字:数组 检查 何检查      更新时间:2023-10-16

我在数组中输入了 4 个数字

for (int i=0;i<4;i++)
{
    cin >> choice[i];
}

我需要检查我是否已在数组中输入数字 1,3,4,6(按任何顺序)

例如:-

if choice[0] == 1 && choice[1] == 3 && choice[2] == 4 && choice[3] == 6
else if ........ 1,3,6,4
else if..........1,6,3,4
else if.......1,6,4,3
else if......1,4,6,3
else if......1,4,3,6
....
....
else if.....6,4,3,1

这种类型的检查使我的代码太大。

请帮助我使用另一种方式

使用 std::is_permutation

int choice[4];
for (int i=0;i<4;i++)
{
    cin >> choice[i];
}
std::cout << std::is_permutation(std::begin(choice), std::end(choice), std::vector<int>{1, 3, 4, 6}.begin()) << std::endl;
bool count1=false;
bool count2=false;
bool count3=false;
bool count4=false;
for (int i=0;i<4;i++)
{
cin >> choice[i];
if(choice[i]==1) count1==true;
else if(choice[i]==3) count2=true;
else if(choice[i]==4) count3=true;
else if(choice[i]==6)  count4=true;
}
if(count1 && count2 && count3 && count4) cout<<endl<<"yes, it is!";

你可以使用这样的东西:

std::vector<int> choice(4);
for (int i = 0; i < 4; ++i)
{
    std::cin >> choice[i];
}
std::sort(std::begin(choice), std::end(choice));
if (choice == std::vector<int>{1, 3, 4, 6}) { // 1, 3, 4, 6 should be sorted.
    // equal
}

活生生的例子。