1. 程式人生 > 其它 >常用查詢演算法之find演算法

常用查詢演算法之find演算法

技術標籤:stl常用演算法

演算法簡介
在這裡插入圖片描述
函式原型:
在這裡插入圖片描述
find查詢自定義資料型別時,要對==運算子進行過載,否則編譯器不知道如何進行p是否等於p1的比較

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<string>
//find演算法
//1.內建資料型別
void test01()
{
	vector<int> v = { 1,2,3,4,5,7 };
	vector<int>::iterator it;
it=find(v.begin(), v.end(), 3); if (it != v.end()) { cout << "查詢到該元素:" << *it << endl; } else { cout << "查不到" << endl; } } //2.自定義資料型別 class person { public: person(string name,int age):name(name),age(age){} string name; int age; //過載==,讓底層find知道如何對比person資料型別
//傳入的引數要加const,不然會報錯 bool operator==(const person& p) { if (p.name == this->name && p.age == this->age) { return true; } else { return false; } } }; void test02() { person p1("孫悟空", 1000); person p2("豬八戒", 800); person p3("沙僧", 500); vector<
person> v = { p1,p2,p3 }; vector<person>::iterator it; //查詢p是否在v容器中存在 person p("孫悟空", 1000); it = find(v.begin(), v.end(), p); //find查詢自定義資料型別時,要對==運算子進行過載,否則編譯器不知道如何進行p是否等於p1的比較 //對比完後返回的是真假,如果為真返回當前迭代器 if (it != v.end()) { cout << "查詢到該元素"<< endl; cout << "姓名: " << (*it).name << " 年齡: " << (*it).age << endl; } else { cout << "查不到" << endl; } } int main() { //test01(); test02(); system("pause"); return 0; }