C++怎样查找序列中是否包含某一个元素?STL之find()算法

假如现在有一个val=5,我想看看某一段序列中是否包含了这个val,应该怎么做呢?STL又提供了find()算法供我们使用,下面我们来介绍一下这个算法。

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

InputIterator
find_if(InputIterator beg,InputIterator end,UnaryPredicate op)
  • 第一形式返回区间[beg,end)中第一个“元素值等于value"的元素位置
  • 第二形式返回区间[beg,end)中令以下一元判断式结果为true的第一个元素 :op(elem)
  • 如果没有找到匹配元素,两种形式都返回end
  • op在函数调用过程中不应该改变自身状态
  • op不应该改动传递来的参数
  • 如果是已序区间,应使用lower_bound(),upper_bound(),equal_range()或binary_search()算法以获取更高性能
  • 关联式容器(sets,multisets,maos,multimaps)提供了一个等效的成员函数find()

下面展示如何让运用find()来搜寻一个子区间:以元素值为4的第一个元素开始,以元素值为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;
	}
}

运行结果如下, 

下面这个程序展示find_if()的用法,以特定的搜寻准则来搜寻某个元素

#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;
}

猜你喜欢

转载自blog.csdn.net/yangSHU21/article/details/130543035