问题
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 ?
回答1:
The difference is that std::search
searches for a whole range of elements within another range, while std::find_first_of
searches for a single element from a range within another range.
回答2:
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.
回答3:
std::search()
finds where the range of elements that matches the entire sequence of [first2..last2)
is, while find_first_of()
finds the first single element that matches one of the elements in [first2..last2)
.
来源:https://stackoverflow.com/questions/21017338/difference-between-stdsearch-and-stdfind-first-of