How does C++ find out whether a sequence contains an element? STL's find() algorithm

If there is a val=5 now, I want to see if this val is included in a certain sequence, how should I do it? STL also provides the find() algorithm for us to use, let's introduce this algorithm below.

InputIterator 
find(InputIterator beg,InputIterator end,const T& value)

InputIterator
find_if(InputIterator beg,InputIterator end,UnaryPredicate op)
  • The first form returns the position of the first "element value equal to value" element in the interval [beg, end)
  • The second form returns the first element in the interval [beg, end) that makes the following unary judgment expression true: op(elem)
  • Both forms return end if no matching element is found
  • op should not change its state during the function call
  • op should not change the passed parameters
  • If it is an ordered range, lower_bound(), upper_bound(), equal_range() or binary_search() algorithms should be used for higher performance
  • Associative containers (sets, multisets, maos, multimaps) provide an equivalent member function find()

Here's how to use find() to search a subrange: starting with the first element with element value 4 and ending with the second element with element value 4:

#include"algostuff.h"
using namespace std;
int main()
{
	list<int> col;
	INSERT_ELEMENTS(col, 1, 9);
	INSERT_ELEMENTS(col, 1, 9);

	PRINT_ELEMENTS(col, "col: "); //col: 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9

	//find first element with value 4
	list<int>::iterator pos1;
	pos1 = find(col.begin(), col.end(), 4);

	//find second element with value 4
	list<int>::iterator pos2;
	if (pos1 != col.end())
	{
		pos2 = find(++pos1, col.end(), 4);
	}

	//print all elements from first to second 4
	cout << "between first 4 and second 4:" << endl;
	if (pos1 != col.end() && pos2 != col.end())
	{
		copy(--pos1, ++pos2, ostream_iterator<int>(cout, " "));
		cout << endl;
	}
}

The result of the operation is as follows, 

The following program demonstrates the use of find_if() to search for an element with specific search criteria

#include"algostuff.h"
using namespace std;
int main()
{
	vector<int> col;
	vector<int>::iterator pos;

	INSERT_ELEMENTS(col, 1, 9);
	PRINT_ELEMENTS(col, "col: ");

	//find first element greater than 3
	pos = find_if(col.begin(), col.end(), bind2nd(greater<int>(), 3));

	//print its position 
	cout << "the " << distance(col.begin(), pos) + 1 << ".element is the first greater than 3" << endl;

	//find first element divisible by 3
	pos = find_if(col.begin(), col.end(), not1(bind2nd(modulus<int>(), 3)));

	//print its position
	cout << "the " << distance(col.begin(), pos) + 1 << ".element is the first divisible by 3" << endl;
}

Guess you like

Origin blog.csdn.net/yangSHU21/article/details/130543035