查找(find-find_if)-1

本文探讨了在C++中使用查找算法(如find和find_if)在不同类型的容器(如list和vector)中搜索元素的方法。同时,深入研究了关联式容器(如set)的特性,包括自动排序和平衡,以及如何在其中进行高效查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//查找算法
//关联式容器已经排序了,速度快
#include<iostream>
#include<string>
#include<set>
#include<list>
#include<algorithm>
#include<vector>
#include<functional>

using namespace std;

int main()
{
	list<int> l;

	for (int i = 0; i <= 9; ++i)
	{
		l.insert(l.end(), i);
	}
	for (int i = 0; i <= 9; ++i)
	{
		l.insert(l.end(), i);
	}

	for (auto iter = l.begin(); iter != l.end(); ++iter)
		cout << *iter << " ";

	cout << endl;

	list<int>::iterator pos1;
	list<int>::iterator pos2;
	pos1 = find(l.begin(), l.end(), 4);
	if (pos1 != l.end())
	{
		pos2 = find(++pos1, l.end(), 4);
	}
	if (pos1 != l.end() && pos2 != l.end())
	{
		for (auto iter = pos1; iter != pos2; ++iter)
			cout << *iter << " ";
	}
	cout << endl;

	vector<int> vec;
	vector<int>::iterator pos;
	for (int i = 1; i <= 9; ++i)
	{
		vec.push_back(i);
	}
	for (auto iter = vec.begin(); iter != vec.end(); ++iter)
	{
		cout << *iter << " ";
	}
	cout << endl;
	pos = find_if(vec.begin(), vec.end(), bind2nd(greater<int>(), 3));//找到了大于3的数
	cout << *pos << endl;
	pos = find_if(vec.begin(), vec.end(), not1(bind2nd(modulus<int>(), 3)));//能够被3整除的数字
	cout << *pos << endl;

	//关联式容器
	set<int>  a;//自动排序,自动平衡的红黑树
	a.insert(43);//插入数据之后,他们会自动排序
	a.insert(78);
	a.insert(24);
	a.insert(66);
	for (set<int>::iterator iter = a.begin(); iter != a.end(); ++iter)
		cout << *iter <<" ";
	cout << endl;


	auto pos3 = a.find(78);
	if (pos3 !=a.end())
		cout << " find ok" << endl;
	else
		cout << "find fail" << endl;

	string s("aaabbsdhd");
	auto pos5 = s.find("bsd");
	if (pos5 != string::npos)
		cout << "ok" << endl;


	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值