search()、find_end() 分别在一个指定的元素序列里查找另一指定子序列的第一次和最后一次出现的位置。
1. search()
/* template <class ForwardIterator1, class ForwardIterator2> ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2); predicate (2) template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate> ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred); */ #include <iostream> // std::cout #include <algorithm> // std::search #include <vector> // std::vector bool mypredicate (int i, int j) { return (i==j); } int main () { std::vector<int> haystack; // set some values: haystack: 10 20 30 40 50 60 70 80 90 for (int i=1; i<10; i++) haystack.push_back(i*10); // using default comparison: int needle1[] = {40,50,60,70}; std::vector<int>::iterator it; it = std::search (haystack.begin(), haystack.end(), needle1, needle1+4); if (it!=haystack.end()) std::cout << "needle1 found at position " << (it-haystack.begin()) << '\n'; else std::cout << "needle1 not found\n"; // using predicate comparison: int needle2[] = {20,30,50}; it = std::search (haystack.begin(), haystack.end(), needle2, needle2+3, mypredicate); if (it!=haystack.end()) std::cout << "needle2 found at position " << (it-haystack.begin()) << '\n'; else std::cout << "needle2 not found\n"; system("pause"); return 0; } /* Output: needle1 found at position 3 needle2 not found 请按任意键继续. . . */
2. find_end()
/* template <class ForwardIterator1, class ForwardIterator2> ForwardIterator1 find_end (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2); predicate (2) template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate> ForwardIterator1 find_end (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred); */ #include <iostream> // std::cout #include <algorithm> // std::find_end #include <vector> // std::vector bool myfunction (int i, int j) { return (i==j); } int main () { int myints[] = {1,2,3,4,5,1,2,3,4,5}; std::vector<int> haystack (myints,myints+10); int needle1[] = {1,2,3}; // using default comparison: std::vector<int>::iterator it; it = std::find_end (haystack.begin(), haystack.end(), needle1, needle1+3); if (it!=haystack.end()) std::cout << "needle1 last found at position " << (it-haystack.begin()) << '\n'; int needle2[] = {4,5,1}; // using predicate comparison: it = std::find_end (haystack.begin(), haystack.end(), needle2, needle2+3, myfunction); if (it!=haystack.end()) std::cout << "needle2 last found at position " << (it-haystack.begin()) << '\n'; system("pause"); return 0; } /* Output: needle1 last found at position 5 needle2 last found at position 3 请按任意键继续. . . */