C++ Algorithm Library - find_first_of() Function


Advertisements

Description

The C++ function std::algorithm::find_first_of() returns an iterator to the first element in the range of (first1,last1) that matches any of the elements in first2,last2. If no such element is found, the function returns last1.

Declaration

Following is the declaration for std::algorithm::find_first_of() function form std::algorithm header.

C++98

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

C++11

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

Parameters

  • first1 − Forward iterator to the initial position of the first sequence.

  • last1 − Forward iterator to the final position of the first sequence.

  • first2 − Forward iterator to the initial position of the second sequence.

  • last2 − Forward iterator to the final position of the second sequence.

  • pred − A binary predicate which accepts two arguments and returns a bool.

Return value

Returns an iterator to the first element in the range of (first1,last1) that matches any of the elements in first2,last2. If no such element is found, the function returns last1.

Exceptions

Throws exception if either element comparison or an operation on an iterator throws exception.

Please note that invalid parameters cause undefined behavior.

Time complexity

Linear.

Example

The following example shows the usage of std::algorithm::find_first_of() function.

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

using namespace std;

bool binary_pred(char a, char b) {
   return (tolower(a) == tolower(b));
}

int main(void) {
   vector<char> v1 = {'f', 'c', 'e', 'd', 'b', 'a'};
   vector<char> v2 = {'D', 'F'};
 
   auto result = find_first_of(v1.begin(), v1.end(), v2.begin(), v2.end(), binary_pred);

   if (result != v1.end())
      cout << "Found first match at location " 
         << distance(v1.begin(), result) << endl;

   v2 = {'x', 'y'};

   result = find_end(v1.begin(), v1.end(), v2.begin(), v2.end(), binary_pred);

   if (result == v1.end())
      cout << "Sequence doesn't found." << endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Found first match at location 0
Sequence doesn't found.
algorithm.htm
Advertisements