求大家帮我看看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();
}
binary_search 的谓语是定义查找规则,即 容器中任意两个元素谁大谁小,需要调用你的 compare
//感觉不如使用
std::find_if(v.begin(),v.end(), [&pp](const Person&p) {return p.name==pp.name;});
binary_search就是STL中已经包含的二分查找算法,能在按规则A排好序的数组上按同样规则A查找某元素。
语法:binary_search (数组名+n1,数组名+n2,值,排序规则名( ) );
binary_search函数可以:
再重复一下前提:二分查找时用的查找规则,要和数组的排序规则一样。
下面将举例说明这两种用法:
首先,为了在C++中使用binary_search函数搜索自定义的数据类型,我们需要定义一个比较函数来告诉binary_search如何比较我们的数据类型。
假设我们要搜索的是一个自定义的Person结构体,包含name和age两个成员变量。我们可以定义一个比较函数,比较两个Person结构体的name成员变量。
struct Person {
std::string name;
int age;
};
bool compareByName(const Person& p1, const Person& p2) {
return p1.name < p2.name;
}
现在我们可以使用binary_search函数来搜索一个存储了Person结构体的vector,并使用compareByName函数进行比较。
std::vector<Person> people = { {"Alice", 25}, {"Bob", 30}, {"Charlie", 20} };
std::sort(people.begin(), people.end(), compareByName);
Person target = { "Bob", 30 };
bool found = std::binary_search(people.begin(), people.end(), target, compareByName);
此时,found将会是true,表示我们在vector中找到了目标元素。
对于第二个案例,如果你能提供具体的代码和错误信息,将更有助于我们帮助你解决问题。请提供相关的代码和错误信息,我们将尽力给出具体的解决方案。