C++常用查找算法–find

  • Post author:
  • Post category:其他





一、查找算法简介

1、find //查找算法

2、find_if //按条件查找算法

3、adjacent_find //查找相邻重复元素

4、binary_search //二分查找法

5、count //统计元素个数

6、count_if //按条件统计元素个数



二、find



1、功能描述

查找指定元素,找到返回指定元素的迭代器,找不到返回结束迭代器end()



2、函数原型

1、find(iterator beg,iterator end,value); //按值查找元素,找到返回指定位置迭代器,找不到返回结束迭代器位置



3、示例

代码如下(示例):

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
  //查找  内置数据类型
void test01() {
	vector<int>v;
	for (int i = 0; i < 10; i++)
	{
		v.push_back(i);
	}
	vector<int>::iterator it=find(v.begin(),v.end(),5);
	if (it == v.end())
	{
		cout << "没有找到!" << endl;
	}
	else
	{
		cout << "找到了:" <<*it<< endl;
	}
}
class Person {
public:
	Person(string name, int age)
	{
		this->m_age = age;
		this->m_name = name;
	}
	//重载== 底层find知道如何对比Person数据类型
	bool operator==(const Person& p)
	{
		if (this->m_name == p.m_name && this->m_age == p.m_age)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	string m_name;
	int m_age;
};
//查找 自定义数据类型
void test02()
{
	vector<Person>v;
	Person p1("aaa", 10);
	Person p2("bbb", 20);
	Person p3("ccc", 30);
	Person p4("ddd", 40);
	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);
	v.push_back(p4);
	vector<Person>::iterator it=find(v.begin(), v.end(), p1);
	if (it == v.end())
	{
		cout << "没有找到!" << endl;
	}
	else
	{
		cout << "找到了,姓名是:" << it->m_name <<" 年龄是:" <<it->m_age<< endl;
	}
}

int main()
{
	test01();
	test02();
	system("pause");
	return 0;
}



三、总结

find可以在容器中找指定的元素,返回值是迭代器。



版权声明:本文为qq_62217723原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。