C++ STL非更易型算法查找元素 find、find_if、find_if_not使用方法

在这里插入图片描述

返回[_First,_Last)区间中第一个元素值等于val的元素位置

在这里插入图片描述

返回[_First,_Last)区间中第一个造成_Pred(elem)为true的元素

在这里插入图片描述

返回[_First,_Last)区间中第一个造成_Pred(elem)为false的元素

如果没有找到,都返回end

如果是已排序区间,应该使用lower_bound()、upper_bound()、equal_range()算法获得更高效能

Associative和unordered容器提供一个等效成员函数find()拥有更好的复杂度

复杂度:线性

辅助函数:

template<typename T>
inline void INSERT_ELEMENTS(T& coll, int first, int last)
{
	for (int i = first; i <= last; ++i)
	{
		coll.insert(coll.end(), i);
	}
}
template<typename T>
inline void PRINT_ELEMENTS(const T & coll, const string& optcstr = "")
{
	cout << optcstr;
	for (auto elem : coll)
	{
		cout << elem << ' ';
	}
	cout << endl;

}
template<typename T>
inline void PRINT_MAPPED_ELEMENTS(const T & coll, string& optcstr = "")
{
	cout << optcstr;
	for (auto elem : coll)
	{
		cout << '[' << elem.first << ',' << elem.second << "] ";
	}
	cout << endl;
}

find()使用例子:

int main()
{
	list<int>coll;
	INSERT_ELEMENTS(coll, 1, 9);
	INSERT_ELEMENTS(coll, 1, 9);
	PRINT_ELEMENTS(coll, "coll: ");
	list<int>::iterator pos1;
	pos1 = find(coll.begin(), coll.end(), 4);
	list<int>::iterator pos2;
	if (pos1 != coll.end())
	{
		pos2 = find(++pos1, coll.end(), 4);
	}
	if (pos1 != coll.end() && pos2 != coll.end())
	{
		copy(--pos1, ++pos2, ostream_iterator<int>(cout, " "));
		cout << endl;
	}

}

在这里插入图片描述

find_if()和find_if_not()例子:

int main()
{
	vector<int>coll;
	vector<int>::iterator pos;
	INSERT_ELEMENTS(coll, 1, 9);
	PRINT_ELEMENTS(coll, "coll: ");

	pos = find_if(coll.begin(), coll.end(), bind(greater<int>(), _1, 3));
	cout << "the " << distance(coll.begin(), pos) + 1 << ". element is the first greater than 3" << endl;
	pos = find_if(coll.begin(), coll.end(), [](int elem) {return elem % 3 == 0;});
	cout << "the " << distance(coll.begin(), pos) + 1 << ". element is the first divisible by 3" << endl;

	pos = find_if_not(coll.begin(), coll.end(), bind(less<int>(), _1, 5));
	cout << "first value >= 5: " << *pos << endl;

}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值