简体   繁体   中英

Difference between std::search and std::find_first_of

I am trying to grasp the difference between std::search and std::find_first_of

They have the same prototypes:

template <class ForwardIterator1, class ForwardIterator2>
   ForwardIterator1 find_first_of (ForwardIterator1 first1, ForwardIterator1 last1,
                                   ForwardIterator2 first2, ForwardIterator2 last2);

template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
   ForwardIterator1 find_first_of (ForwardIterator1 first1, ForwardIterator1 last1,
                                   ForwardIterator2 first2, ForwardIterator2 last2,
                                   BinaryPredicate pred);

template <class ForwardIterator1, class ForwardIterator2>
   ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1,
                            ForwardIterator2 first2, ForwardIterator2 last2);

template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
   ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1,
                            ForwardIterator2 first2, ForwardIterator2 last2,
                            BinaryPredicate pred);

They both return the same thing: An iterator to the first occurrence of the sequence [first2, last2) inside [first1, last1). (using equality, or a binary predicate)

So what is the difference ? Am I wrong ?

区别在于std::search搜索另一个范围内的整个元素范围,而std::find_first_of搜索另一个范围内的单个元素。

std::find_first_of is looking for any of the elements in your search range. It will return an iterator to the first occurrence of any of the elements in [s_first1, s_first2] .

std::search is looking for the whole sequence you passed. Such, it will return an iterator to the first occurrence of the sequence [s_first1, s_first2] .

#include <vector>
#include <iostream>
#include <algorithm>

int main() {
    std::vector<int> A{1, 2, 3, 2, 4, 6, 5};
    std::vector<int> search_range{2, 4, 6};
    std::vector<int> find_first_of_range{6, 5};

    auto it_search = std::search(A.begin(), A.end(),
        search_range.begin(), search_range.end());
    std::cout << std::distance(A.begin(), it_search) << std::endl; // 3

    auto it_find_first_of = std::find_first_of(A.begin(), A.end(),
        find_first_of_range.begin(), find_first_of_range.end());
    std::cout << std::distance(A.begin(), it_find_first_of) << std::endl; // 5
}

Runnable on Coliru.

std::search()发现,其中元件的那个的整个序列相匹配的范围内[first2..last2)虽然find_first_of()发现匹配的元素之一的第一单一元件[first2..last2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM