黑马程序员C++提高13——常用的查找算法【find、binary_seach、adjacent_find、find_if、count_if】

在这里插入图片描述

#include<vector>		//向量容器vector
#include<algorithm>		//算法的头文件
#include<iostream>
using namespace std;
//find 算法
//自定义类
class Person {
    
    
public:
	Person(int id, int age):id(id), age(id){
    
    }
	//重载"=="运算符
	bool operator==(const Person& p) {
    
    
		return p.id == this->id && p.age == this->age;
	}
public:
	int id;
	int age;
};
void test01() {
    
    
	vector<Person> v;
	Person p1(1, 20), p2(2, 18), p3(3, 22);
	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);

	//find底层是直接用==判断
	//容器中存放的是对象,不知道如何进行==判断
	//所以要在类中进行"=="符号的重载
	vector<Person>::iterator ret = find(v.begin(), v.end(), p1);

	if (ret == v.end()) {
    
    
		cout << "没找到" << endl;
	}
	else {
    
    
		cout << "找到了" << endl;
	}
}

//binary_search 二分查找法
void test02() {
    
    

	vector<int> v;
	for (int i = 0; i < 6; i++) {
    
    
		v.push_back(i);
	}

	//返回bool类型,只能用于判断是否查找到
	//只能用于有序数据
	bool ret = binary_search(v.begin(), v.end(), 4);

	if (ret) {
    
    
		cout << "没找到" << endl;
	}
	else {
    
    
		cout << "找到了" << endl;
	}
}

//adjacent_find 算法
void test03() {
    
    

	vector<int> v;
	for (int i = 0; i < 6; i++) {
    
    
		v.push_back(i);
	}
	v.push_back(5);

	//查找相邻重复元素
	vector<int>::iterator ret = adjacent_find(v.begin(), v.end());

	if (ret == v.end()) {
    
    
		cout << "没找到相邻重复元素" << endl;
	}
	else {
    
    
		cout << "找到了相邻重复元素:" << *ret << endl;
	}
}

//find_if 算法
bool MySearch(int val) {
    
    
	return val > 3;
}
void test04() {
    
    

	vector<int> v;
	for (int i = 0; i < 6; i++) {
    
    
		v.push_back(i);
	}

	//find_if会根据我们的条件函数,返回第一个满足条件的元素的迭代器
	//即找到第一个使自定义规则MySearch返回true的元素ch);
	vector<int>::iterator ret = find_if(v.begin(), v.end(), MySearch);
	if (ret == v.end()) {
    
    
		cout << "没找到" << endl;
	}
	else {
    
    
		cout << "找到了" << endl;
	}
}

//count 和 count_if 算法
bool MySearch2(int val) {
    
    
	return val > 2;
}
void test05() {
    
    

	vector<int> v;
	for (int i = 0; i < 6; i++) {
    
    
		v.push_back(i);
	}
	v.push_back(4);

	//count 算法,统计元素出现的次数
	int num = count(v.begin(), v.end(), 4);
	cout << "元素4出现的次数:" << num << endl;

	//count 算法,统计满足自定义规则的元素出现的次数
	//这里自定义的是元素>2,即统计>2的元素的个数
	num = count_if(v.begin(), v.end(), MySearch2);
	cout << ">2的元素的个数:" << num << endl;
}

//简单测试
int main() {
    
    
	//test01();
	//test02();
	//test03();
	//test04();
	test05();

	cout << endl << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43685399/article/details/108611271