如何检查数组是否包含多个元素?

How can I check if a array contains multiple elements?

我正在尝试查看一个数组是否在数组中的任何给定索引处包含多个值,如果包含,我希望它 return 为真,否则 return 为假。我希望它在找到数字 1-9 时 return 为真,否则为假。

 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++。所以使用标准向量和标准库中的 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;});

Return值为1的元素个数。

也好,问一下1有没有值:

std::any_of(std::begin(a), std::end(a), [](auto const& x){ return x == 1;});

我知道这绝对不是答案...

基本上,您的代码与任何 C++ 准则相去甚远。

首先,您不会在 C++ 中将数组作为 int a[] 传递。请改用 std::vector<int>

其次,您的算法效率极低。考虑使用直方图方法。

bool isSolved(const std::vector<int>& a)
{
     std::array<bool,10> hist;
     for(int i=0; i<10; i++)
     {
         hist[i]=false;
     }
     for(auto x : a)
     {
         if(x>=0 && x<10)
         {
              hist[x] = true;
         }
     }

     for(int i=0; i<10; i++)
     {
         if(!hist[i]) return false;
     }
     return true;
}

I am trying to see if an array contains multiple values at any given index in the array

数组的每个索引始终只包含一个值。

hasNum 函数中不需要 2 个 for 循环。此外,如果数组中的任何值不等于传递的数字,则您 returning 为 false。 for循环结束后需要return false。

重写您的 hasNum 函数,如下所示:

bool hasNum(int a[], int size, int num) {

    for (int i = 0; i < size; i++) {
        if (a[i] == num) {
            return true;
        }
    }
    return false;
}

以下是解决您的问题的提示:

class BinaryTreeSet : public BinarySearchTree {
    ...
    operator==
    ...
};

您最好使用标准算法,例如 find_if:

#include <algorithm>
int a[42]; // or vector<int> a(42) or any other container of any size
std::find_if(std::begin(a),std::end(a),[](auto const& v){return (v>=1)&&(v<=9);});