正确答案
// ConsoleApplication2.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//严重性 代码 说明 项目 文件 行 禁止显示状态
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include <algorithm>
#include<vector>
#include<string>
#include<ctime>
#include<cstring>
const int L = 10;
class Person
{
public:
Person(string name, int age);
~Person();
bool operator<(const Person& p) //需要排序前提的算法一般需要重载<
{
//return this->m_Age < p.m_Age;
char str1[L],str2[L];
strcpy(str1, this->m_Name.c_str());
strcpy(str2, p.m_Name.c_str());
int ret = strcmp(str1,str2);
if (ret == -1)
{
return 1;
}
else
return 0;
}
private:
string m_Name;
int m_Age;
friend void test02();
friend class MyPrint;
friend class MyCompare;
friend bool myCompare(const Person& p1, const Person& p2);
};
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;
}
};
//普通函数排序
bool myCompare(const Person& p1, const Person& p2)
{
return p1.m_Name > p2.m_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;
}
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);
//1用仿函数
//int result = binary_search(v.begin(), v.end(),pp, MyCompare());
//2用普通函数
//int result = binary_search(v.begin(), v.end(), pp,myCompare);
//3用匿名函数
int result = binary_search(v.begin(), v.end(), pp, [](const Person& p1, const Person& p2) {return p1.m_Name > p2.m_Name; });
//4其他方法
//auto it=std::find_if(v.begin(), v.end(), [&pp](const Person&p) {return p.m_Name == pp.m_Name; });
//if (it!=v.end())
//{
// cout << "已找到" << endl;
// cout << it->m_Name << "\t" << it->m_Age << endl;
//}
//else
//cout << "未找到" << endl;
if (result == 1)
{
cout << "已找到" << endl;
}
else
cout << "未找到" << endl;
}
int main()
{
//test01();
test02();
}