// c2011.cpp : 定义控制台应用程序的入口点。
//
//#include "stdafx.h"
#include <vector>
#include <map>
//#include <regex>
#include <algorithm>
#include <functional>
#include <array>
#include <iostream>
#include <sstream>
using namespace std;
class record_t
{
private:
public:
int m_groupid;
double m_fee;
float m_price;
std::string m_name;
public:
record_t():m_name(""),m_fee(0),m_groupid(0),m_price(0)
{
//
}
record_t(const std::string &name,double fee,int groupid,float price)
:m_name(name),m_fee(fee),m_groupid(groupid),m_price(price)
{
//
}
//运算符operator <<重载,友元声明支持访问record_t的private变量
friend inline ostream &operator <<(ostream &os,const record_t &r)
{
os<<"m_fee->"<<r.m_fee<<"##m_groupid->"
<<r.m_groupid<<"##m_name->"<<r.m_name
<<"m_price:"<<r.m_price<<endl;
return os;
}
const std::string getName() const
{
return m_name;
}
double getFee() const
{
return m_fee;
}
int getGroupId() const
{
return m_groupid;
}
void destroy()
{
delete this;
}
};
template<typename T,typename R> class compare_t: public std::unary_function<T,R>
{
private:
//比较规则
int m_rule;
public:
compare_t(int rule):m_rule(rule)
{
//
}
//支持T& 比较
//R operator()(T &t1,T &t2)
//{
//return compare(t1,t2);
//}
//支持const T& 比较
R operator()(const T &t1,const T &t2)
{
return compare(t1,t2);
}
//支持T* 指针比较
//R operator()(T *t1,T *t2)
//{
//return compare(*t1,*t2);
//}
//支持const T* 指针比较
R operator()(const T *t1,const T *t2)
{
return compare(*t1,*t2);
}
//实现比较规则
R compare(const T &t1,const T &t2)
{
R result = false;
switch(m_rule)
{
case 1:
{
result = t1.getName() < t2.getName()?true:false;
break;
}
case 2:
{
result = t1.getFee() < t2.getFee()?true:false;
break;
}
default:
{
result = (t1.getGroupId() > t2.getGroupId())?true:false;
break;
}
}
return result;
}
};
int main(int argc, char* argv[])
{
std::array<std::string,10> aa;
std::fill_n(aa.begin(),aa.size(),"aa");
std::string total = "";
//lambda 表达式[¶meter1,¶meter2,...](parameterlist)
std::for_each(aa.begin(),aa.end(),[&total](std::string &i){
total += (total.empty()?"":"#") + i;
});
std::cout<<total<<endl;
//预先分配内存
const unsigned int SIZE = 10;
std::vector<record_t*> rr(SIZE);
for(size_t i = 0,j = SIZE;i < SIZE;++i,--j)
{
rr[i] = new record_t("AA",j,i,(float)i);
}
//指定比较规则
int compare_rule = 1;
compare_t<record_t,bool> comp = compare_t<record_t,bool>(compare_rule);
std::sort(rr.begin(),rr.end(),comp);
//简写
std::sort(rr.begin(),rr.end(),compare_t<record_t,bool>(compare_rule));
for(size_t i = 0;i < SIZE;++i)
{
std::cout<<(*rr[i])<<endl;
}
std::vector<record_t> rrr(SIZE);
std::sort(rrr.begin(),rrr.end(),compare_t<record_t,bool>(compare_rule));
std::vector<const record_t> rrrr(SIZE);
std::sort(rrrr.begin(),rrrr.end(),compare_t<record_t,bool>(compare_rule));
std::vector<const record_t*> rrrrr(SIZE);
std::copy(rr.begin(),rr.end(),rrrrr.begin());
std::sort(rrrrr.begin(),rrrrr.end(),compare_t<record_t,bool>(compare_rule));
//析构对象,释放内存
std::for_each(rr.begin(),rr.end(),std::mem_fun(&record_t::destroy));
rr.clear();
system("pause");
return 0;
}