#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;
}
这里补充回答下面一位小伙伴问的问题
binary_search怎么查找自定义数据类型
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
//这里自定义数据类型
class Person {
public:
Person(int age = 0, int num = 0):m_age(age), m_num(num){}
public:
int m_age;
int m_num;
};
//自定义查找函数
//由于二分查找法需要有序,所以在这里要规定一个排序的规则
//底层知道你是根据这个规则进行排序的话,也就能够知道怎么查找了
bool MySearch(const Person& p1, const Person& p2) {
return p1.m_age > p2.m_age;
}
void test() {
Person p1(11, 01), p2(22, 02), p3(33, 03), p4(44, 04);
vector<Person> v;
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
Person FindPerson;
int findAge = 33;
FindPerson.m_age = findAge;
bool ret = binary_search(v.begin(), v.end(), FindPerson, MySearch);
if (ret) {
cout << "没找到" << endl;
}
else {
cout << "找到了" << endl;
}
}
//测试
int main() {
test();
cout << endl << endl;
return 0;
}