我试图查看一个数组是否在数组中的任何给定索引处包含多个值,如果包含,我希望它返回 true,否则返回 false。我希望它在找到数字 1-9 时返回 true,否则返回 false。
bool isSolved(int a[], int size) {
int count = 0;
for (int i = 1; i < 10; i++) {
if (hasNum(a,size,i)) {
count++;
}
}
if (count == 9) {
return true;
}
else {
return false;
}
}
bool hasNum(int a[], int size, int num) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (a[j] == num) {
return true;
}
else {
return false;
}
}
}
}
这是我目前所拥有的,它只是卡住了,永远不会结束。
最佳答案
伙计,那是 C++。所以使用标准 vector 和标准库中的 count_if 函数:
#include <algorithm>
#include <vector>
std::vector<int> a { /* fill vector */ };
std::count_if(std::begin(a), std::end(a), [](auto const& x){ return x == 1;});
返回值为 1
的元素的数量。
也很好,质疑1
是否有任何值(value):
std::any_of(std::begin(a), std::end(a), [](auto const& x){ return x == 1;});
我知道这绝对不是答案......
关于c++ - 如何检查数组是否包含多个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57998061/