请问如何利用运算符重载完成merge
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<string>
#include<ctime>
#include<functional>
class Person
{
public:
Person()
{
}
Person(string name, int age);
~Person();
bool operator<(const Person& p)
{
if (this->m_Age < p.m_Age)
{
return 1;
}
else
return 0;
}
private:
string m_Name;
int m_Age;
friend void test02();
friend class MyPrint;
friend class MyCompareUP;
friend class MyCompareDown;
};
Person::Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
}
Person::~Person()
{
}
class MyCompareUP
{
public:
bool operator()(const Person& p1, const Person& p2)
{
return p1.m_Age < p2.m_Age;
}
};
class MyCompareDown
{
public:
bool operator()(const Person& p1, const Person& p2)
{
return p1.m_Age > p2.m_Age;
}
};
class MyPrint
{
public:
void operator()(const Person& p)
{
cout << "姓名" << p.m_Name << "年龄" << p.m_Age << endl;
}
};
void myPrint(int c)
{
cout << c << " ";
}
void test01()
{
vector<int>v,v2,v3;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
v2.push_back(i+1);
}
cout << "升序合并" << endl;
// sort(v.begin(), v.end());
// sort(v2.begin(), v2.end());
v3.resize(v.size() + v2.size());
merge(v.begin(), v.end(), v2.begin(), v2.end(), v3.begin());
for_each(v3.begin(), v3.end(), myPrint); cout << endl;
v3.clear();
cout << "降序合并" << endl;
sort(v.begin(), v.end(),greater<int>());
sort(v2.begin(), v2.end(),greater<int>());
v3.resize(v.size() + v2.size());
merge(v.begin(), v.end(), v2.begin(), v2.end(), v3.begin(),greater<int>());
for_each(v3.begin(), v3.end(), myPrint); cout << endl;
v3.clear();
}
void test02()
{
vector<Person>v,v2,v3;
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));
}
Person pp("C", 0);
v2.push_back(pp);
cout << "升序合并" << endl;
sort(v.begin(), v.end(),MyCompareUP());
sort(v2.begin(), v2.end(),MyCompareUP());
v3.resize(v.size() + v2.size());
merge(v.begin(), v.end(), v2.begin(), v2.end(), v3.begin(),[](const Person& p1,const Person& p2){return p1<p2;});
for_each(v3.begin(), v3.end(), MyPrint()); cout << endl;
v3.clear();
cout << "降序合并" << endl;
sort(v.begin(), v.end(),MyCompareDown());
sort(v2.begin(), v2.end(),MyCompareDown());
v3.resize(v.size() + v2.size());
merge(v.begin(), v.end(), v2.begin(), v2.end(), v3.begin(), [](const Person& p1,const Person& p2){return p1>p2;});
for_each(v3.begin(), v3.end(), MyPrint()); cout << endl;
v3.clear();
}
int main()
{
test01();cout<<endl<<endl;
test02();cout<<endl<<endl;
}