我用了三个打印方法,然后插入了一些数据,但是没有输出,麻烦大家看看哪里出问题了
map<Person,int,MyCompare>
Person里面有年龄,我想按年龄排序;还有姓名
int是编号
MyCompare是伪函数
#include<iostream>
using namespace std;
#include<map>
#include<string>
#include<algorithm>
class MyCompare;
class Person
{
private:
int m_Age;
string m_Name;
public:
Person(int age, string name)
{
this->m_Age = age;
this->m_Name = name;
}
friend class MyCompare;
friend class PrintElement;
friend void printElement(const pair<Person, int>& element);
friend void showElement(const map<Person,int,MyCompare>& m);
};
/*
template <class T>
class greater : binary_function <T,T,bool>
{
public:
bool operator() (const T& x, const T& y) const //常函数
{return x>y;}
};
*/
//仿函数排序
class MyCompare
{
public:
//bool operator()(int v1, int v2)
//{
// return v1 > v2;
//}
bool operator()(const Person& p1,const Person& p2)const
{
return p1.m_Age > p2.m_Age;
}
// bool operator()(const pair<Person, int>& p1,const pair<Person, int>& p2)const
// {
//
// return p1.first.m_Age > p2.first.m_Age;
// }
};
//仿函数打印
class PrintElement
{
public:
void operator()(const pair<Person, int>& element)
{
cout << element.first.m_Name<<","<< element.first.m_Age<< ", " << element.second << endl;
}
};
// 普通函数打印
void printElement(const pair<Person, int>& element)
{
cout << element.first.m_Name<<","<< element.first.m_Age<< ", " << element.second << endl;
}
//迭代器打印
void showElement(const map<Person,int,MyCompare>& m)
{
for(map<Person,int,MyCompare>::const_iterator it=m.begin();it!=m.end();it++)
{
cout<<it->first.m_Name<<"\t"<<it->first.m_Age<<"\t"<<it->second<<endl;
}
}
int main()
{
Person p[3] = { Person(18,"张三"),Person(19,"李四"),Person(20,"王五") };
map<Person,int,MyCompare>m;
for (int i = 0; i != 3; i++)
{
m.insert( make_pair(p[i],++i) );
}
for_each(m.begin(), m.end(), PrintElement());
for_each(m.begin(), m.end(), printElement);
showElement(m);
}