如何检查数组中的值
How to check for a value in an array
我在数组中输入了 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
}
活生生的例子。
相关文章:
- 试图让变量检查数组中的某些内容
- 如何在C++中检查2D数组中负值的输入验证
- 使用for循环检查数组中的重复项
- 检查TCHAR数组输入是否为带符号整数C++
- std::数组边界检查如何工作?
- 检查输入 std::array 指针数据是否等于某个常量数组
- 给定一个大小为 N 的数组 S,检查是否可以将序列拆分为两个序列
- C++ 检查结果数组中有多少次数字
- 检查数组中是否有字符串中的值,如果没有,则添加它
- 有没有办法在c ++中清除空数组,请检查下面的代码以获取说明
- 如何检查一个字符是否与字符数组中的另一个字符匹配?
- 如何检查二维数组上的周围数字?
- 检查反向数组是否与原始数组相同
- 如何检查cin是否与数组中的一组数字匹配
- 如何检查数组中是否没有值
- 如何检查字节数组是protobuf序列化字节数组还是普通字节数组
- 检查彩虹数组(检查数组的反向样式是否与自身匹配)
- 使用数组检查连续性
- c++ 根据随机生成的数组检查用户输入的值
- 使用字符串数组检查用户输入