在 C++ 中检查数组是否包含某元素

在 C++ 中使用数组时,可能还需要在 C++ 中检查一个数组是否包含一个元素。虽然这可以简单地使用循环来完成,但其他有效的方法也可以做到这一点。

本文将指导你通过各种方法检查 C++ 中的数组中是否存在元素。继续阅读。

C++ 的标准库提供了一些算法和函数,我们可以使用它们来检查数组是否包含 C++ 中的元素。但是让我们首先看看如何使用循环来做到这一点。

在 C++ 中使用循环来检查一个数组是否包含某元素

你可以使用 for 循环使事情变得非常简单。在下面的代码中,我们有一个名为 points 的数组和一个我们必须搜索的名为 key 的元素。

main 块内,我们使用 for 循环线性遍历所有元素。在每次迭代中,我们检查当前元素是否与我们正在寻找的元素相同。

如果找到了 key 元素,循环中断,布尔变量 present 的值更新为 false。稍后,根据这个变量的值 present,我们打印所需的输出。

示例代码:

#include<iostream>#include<algorithm>using namespace std;
int main()
{
    int points[] = {23, 45, 56, 12, 34, 56};
    int key = 56;
    bool present = false;
    for(int i:points){
        if(i == key){
            present = true;
            break;
        }
    }
    if (present){
        cout << "The element is present";
    }else{
        cout << "The elment is not present";
    return 0;
}

输出:

The element is present

虽然这是在数组中搜索元素的最简单方法,但还有其他更好的方法可以做到这一点。我们将在以下部分讨论它们。

在 C++ 中使用 std::find 来检查一个数组是否包含某元素

std::find 函数主要用于搜索特定范围内的元素。此函数在范围 [first, last) 之间搜索所需的元素。

语法:

InputIterator find(InputIterator first, InputIterator last, const T& val);

下面是使用 std::find 函数在数组中搜索元素的代码。在这里,我们使用布尔变量 presentstd::find 函数来迭代数组 points

std::find 函数接受三个参数:

  1. 变量 points,作为数组初始位置的迭代器
  2. 表达式 points+x,作为数组最后位置的迭代器
  3. 变量 key,这是要搜索的值

如果未找到值,此函数将迭代器返回到数组的末尾,但我们可以根据变量 present 值打印所需的语句。

示例代码:

#include<iostream>#include<algorithm>using namespace std;
int main()
{
    int points[] = {23, 45, 56, 12, 34, 56};
    int key = 56;
    int x = sizeof(points) / sizeof(*points);
    bool present = std::find(points, points+x, key) != points + x;
    if (present){
        cout << "The element is present";
    }else{
        cout << "The element is not present";
    }
    return 0;
}

输出:

The element is present

如果传递上述参数令人困惑,你还可以分别使用 begin()end() 函数将两个迭代器传递到数组的开头和结尾。

示例代码:

#include<iostream>#include<algorithm>using namespace std;
int main()
{
    int points[] = {23, 45, 56, 12, 34, 56};
    int key = 56;
    bool present = std::find(begin(points), end(points), key) != end(points);
    if (present){
        cout << "The element is present";
    }else{
        cout << "The element is not present";
    }
    return 0;
}

输出:

The element is present

看看我们如何直接使用 begin()end() 函数来简化代码。它就像前面代码中的参数一样工作。

在 C++ 中使用 Std::Count 来检查一个数组是否包含某元素

另一种方法是使用算法 std::count。本质上,该算法计算元素在给定范围内出现的次数。

如果计数的返回值不为零,这意味着该元素存在于数组中。std::count 算法还计算范围 [first, last) 之间元素的出现次数。

语法:

int counter(Iterator first, Iterator last, T &val)

查看代码以了解其工作原理。

#include<iostream>#include<algorithm>using namespace std;
int main()
{
    int points[] = {23, 45, 56, 12, 34, 56};
    int key = 56;
   cout << std::count(begin(points), end(points), key);
}

输出:

2

看看我们如何将所需的参数传递给这个函数并打印结果。由于 key56 出现在数组 points 中的两个位置,我们得到输出为 2

现在,我们将它与布尔变量 present 合并,以检查 key 变量的计数是否大于零。如果是,则仅表示该元素存在于数组中。

#include<iostream>#include<algorithm>using namespace std;
int main()
{
    int points[] = {23, 45, 56, 12, 34, 56};
    int key = 56;
    bool present = std::count(begin(points), end(points), key) > 0;
    if (present){
        cout << "The element is present";
    }else{
        cout << "The element is not present";
    }
    return 0;
}

输出:

The element is present

自然,该算法的性能比 std::find 慢,因为它遍历整个数组以查找元素的计数。

在 C++ 中使用 std::binary_search 来检查一个数组是否包含某元素

如果数组已排序,在 C++ 中检查数组是否包含元素的最有效方法是使用二进制搜索算法。C++ 的标准库提供了一个 binary_search 算法来做同样的事情。

如果在 [first, last) 范围内找到元素,std::binary_search 算法将返回值 true。否则,它返回 false

在下面的代码中,我们创建了一个名为 checkEle() 的函数,其中我们首先使用 sort() 函数对数组进行排序,然后使用 std::binary_search 算法搜索 key 元素.

示例代码:

#include<iostream>#include<algorithm>using namespace std;
bool checkEle(int a[], int x, int key)
{
    if (x <= 0){
        return false;
    }
    sort(a, a+x);
    return std::binary_search(a, a+x, key);
}
int main()
{
    int points[] = {23, 45, 56, 12, 34, 56};
    int key = 56;
    int x = sizeof(points) / sizeof(*points);
    bool present = checkEle(points, x, key);
    if (present){
        cout << "The element is present";
    }else{
        cout << "The element is not present";
    }
    return 0;
}

输出:

The element is present

这仅在数组已经排序时有用,因为首先使用 sort() 函数对数组进行排序会进一步增加时间复杂度。

在 C++ 中使用 any_of() 函数来检查一个数组是否包含某元素

我们可以使用 any_of() 函数来检查谓词是否符合给定范围内的任何元素。如果是,则返回 true;否则,它返回 false

语法:

template <class InputIterator, class UnaryPredicate>
bool any_of (InputIterator begin, InputIterator end, UnaryPredicate p);

查看代码以了解谓词是如何定义的。在这里,除了调用 any_of() 函数外,我们还使用 and 条件来同时检查当前元素是否等于我们正在搜索的 key

如果任何元素都满足条件,则布尔变量 present 的值将更新为 true

#include<iostream>#include<algorithm>#include<array>using namespace std;
int main()
{
    int points[] = {23, 45, 56, 12, 34, 56};
    int key = 56;
    bool present = std::any_of(begin(points), end(points),
                        [&](int i) {
                            return i == key;
                        });
    if (present){
        cout << "The element is present";
    }else{
        cout << "The element is not present";
    }
    return 0;
}

输出:

The element is present

这就是 any_of() 函数如何在数组中搜索元素的方式。这就是我们如何在 C++ 中搜索数组中的元素。

结论

本文讨论了在 C++ 中检查数组是否包含元素的各种方法。我们看到了如何在 C++ 中使用简单的 for 循环,并且还使用了诸如 std::findstd::countstd::binary_search 等算法。

虽然,所有这些方法都达到了相同的目标。完全由你决定你喜欢的最佳方法。