求大家帮我看看binary_search如何完成自定义数据类型搜索,主要是第二个案例
#include <iostream>
using namespace std;
#include <algorithm>
#include<vector>
#include<string>
#include<ctime>
class Person
{
public:
Person(string name, int age);
~Person();
bool operator==(const Person& p)
{
if (this->m_Name == p.m_Name)
{
return 1;
}
else
return 0;
}
bool operator<(const Person& p) //需要排序前提的算法一般需要重载<
{
return this->m_Age<p.m_Age ;
}
private:
string m_Name;
int m_Age;
friend void test02();
friend class MyPrint;
friend class MyCompare;
friend class MySearch;
friend bool mySearch(const Person& p,const string& name);
};
Person::Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
}
Person::~Person()
{
}
class MyPrint
{
public:
void operator()(const Person& p)
{
cout << "姓名" << p.m_Name << "年龄" << p.m_Age << endl;
}
};
class MyCompare
{
public:
bool operator()(const Person& p1, const Person& p2)
{
return p1.m_Name > p2.m_Name;
}
};
class MySearch
{
public:
bool operator()(const Person& p,const string& name)const
{
return p.m_Name==name;
}
};
void test01()
{
vector<int>v;
for (int i = 0; i < 9; i++)
{
v.push_back(i);
}
int result=binary_search(v.begin(), v.end(), 6);
if (result == 1)
{
cout << "已找到" << endl;
}
else
cout << "未找到" << endl;
}
bool mySearch(const Person& p,const string& name)
{
return p.m_Name==name;
}
void test02()
{
vector<Person>v;
char nameSeed[3][2] = { "A","B","C" };
srand((unsigned int)time(NULL));
for (int i = 0; i < 3; i++)//赋值
{
int age = rand() % 100 + 1;
v.push_back(Person((const char*)nameSeed[i], age));
}
sort(v.begin(), v.end(), MyCompare());//先排序
for_each(v.begin(), v.end(), MyPrint()); cout << endl;
Person pp("B", 0);//我不会看底层代码,觉得底层因该是用到==重载,我用对象pp去找v的第二个元素''B"
int result = binary_search(v.begin(), v.end(),pp,MySearch());
if (result == 1)
{
cout << "已找到" << endl;
}
else
cout << "未找到" << endl;
}
int main()
{
test01();
test02();
}