001常用的查找算法find

/*
 * find //查找元素
find_if //按条件查找元素
adjacent_find //查找相邻重复元素
binary_search //二分查找法
count //统计元素个数
count_if //按条件统计元素个数
=====================================
功能描述:
查找指定元素,找到返回指定元素的迭代器,找不到返回结束迭代器end()
函数原型:
find(iterator beg, iterator end, value);
// 按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置
// beg 开始迭代器
// end 结束迭代器
// value 查找的元素
 */
#include<iostream>
#include <set>
#include <functional>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;

void test01()
{
	vector<int>v;
	for (int i=0;i<10;i++)
	{
		v.push_back(i);
	}
	//查找容器中是否有5这个元素
	vector<int>::iterator it=find(v.begin(),v.end(),5);
	if (it!=v.end())
	{
		cout<<"找到元素"<<*it<<endl;
	}
}

class Person
{
public:
	Person(string name,int age);
	bool operator==(const Person&p)//重载==运算符,里面要进行判断,所以要重载==运算符。需要告诉底层怎么进行判断
	{
		if (this->m_Name==p.m_Name&&this->m_age==p.m_age)
		{
			return true;
		}
		else { return false; }
	}
public:
	string m_Name;
	int m_age;
};

Person::Person(string name, int age)
{
	m_Name=name;
	m_age=age;
}

void test02()
{
	vector<Person> v;
	//创建数据
	Person p1("aaa",10);
	Person p2("bbb",20);
	Person p3("ccc",30);

	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);
	vector<Person>::iterator it=find(v.begin(),v.end(),p2);//查找是否存在p2这个元素

	if (it!=v.end())
	{
		cout<<"找到p2元素"<<endl;
		cout<<"名字"<<it->m_Name<<endl;
		cout<<"年龄"<<it->m_age<<endl;
	}
}


int main(void)
{
	test01();
	test02();
	system("pause");
	return 0;
}
/*
 * 总结: 利用find可以在容器中找指定的元素,返回值是迭代器
 * =======================================================
 * 找到元素5
找到p2元素
名字bbb
年龄20
请按任意键继续. . .


 */

猜你喜欢

转载自blog.csdn.net/baixiaolong1993/article/details/89645360
今日推荐