Map with comparator(functor)

#include <iostream>
#include <map>
#include <string>

using namespace std;

class Employee {
   friend class EmployeeLessThan;
public:
   Employee(const string& first, const string& last) : lastName_(last), firstName_(first) {}

   string getFirstName( ) const {return(firstName_);}
   string getLastName( ) const {return(lastName_);}
private:
   string lastName_;
   string firstName_;
};

class EmployeeLessThan {
public:
   bool operator( )(const Employee& emp1, const Employee& emp2) const {
      if (emp1.lastName_ < emp2.lastName_)
         return(true);
      else if (emp1.lastName_ == emp2.lastName_)
         return(emp1.firstName_ < emp2.firstName_);
      else
         return(false);
   }
};

int main( ) {

   map<Employee, string, EmployeeLessThan> empMap;

   Employee emp1("B", "A"),emp2("J", "G"),emp3("F", "S"),emp4("G", "G");

   empMap[emp1] = "tester";
   empMap[emp2] = "coder";
   empMap[emp3] = "programmer";
   empMap[emp4] = "developer";

   for (map<Employee, string, EmployeeLessThan>::const_iterator p =
        empMap.begin( ); p != empMap.end( ); ++p) {
      cout << p->first.getFirstName( ) << " " << p->first.getLastName( ) << " is " << p->second << endl;
   }
}
/* 
B A is tester
G G is developer
J G is coder
F S is programmer

 */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值