使用 std::find() 搜索多个元素

Searching for multiple elements using std::find()

是否可以使用 std::find() 一次调用搜索多个元素?示例:std::find(vector.begin(), vector.end(), 0&&1&&D)

谢谢

C++ Reference 说得很清楚:

"An iterator to the first element in the range that compares equal to val. If no elements match, the function returns last."

所以你不能仅通过一个函数调用来完成。

您不能使用 std::find。假设 0&&1&&D 是一个包含三个值的列表,并且您试图在向量中查找具有这些值中的任何一个的元素,您可以使用:

  • std::find_if 带有谓词(lambda 可能是最简单的,例如 [](const T& x) { return x == 0 || x == 1 || x == d; },其中 T 是您的 vector 持有的任何类型),或

  • std::find_first_of(链接页面有一个很好的例子)。

std::for_each 可能适合你。

std::for_each(vector.begin(),
              vector.end(),
              [](auto& item) -> void {if (item == <xxx> ) { /* Use the item */ });

您在评论中提问:

This may be a separate question, but is there a method i can use to search in a vector if certain elements are present?

std::any_of 就是这个功能。

bool found = std::any_of(vector.begin(),
                         vector.end(),
                         [](auto& item) -> bool { return item == <xxx>; });

如果您需要三个值相邻,那么自己实施 find() 可能是最简单的选择:

template <class Iterator, class T>
Iterator find_by_three_values(Iterator first, Iterator last, T value1, T value2, T value3)
{
    for (; first != last; ++first) {
        if (*first == value1
            && first + 1 != last && *(first + 1) == value2
            && first + 2 != last && *(first + 2) == value3) {
            return first;
        }
    }
    return last;
}