修改stl::set相关源码,提供有序属性值的查找接口

普通的stl::set,查找时只能传入key_type。 不能使用属性值查找。

例如:

 1 /* an employee record holds its ID, name and age */
 2 class employee
 3 {
 4 public:
 5   int         id;
 6   std::string name;
 7   int         age;
 8 public:
 9   employee():id(0){}
10   employee(int id_,std::string name_,int age_):id(id_),name(name_),age(age_){}
11   employee(const employee& e2)
12   {
13       *this = e2;
14   }
15 
16   friend std::ostream& operator<<(std::ostream& os,const employee& e)
17   {
18     os<<e.id<<" "<<e.name<<" "<<e.age<<std::endl;
19     return os;
20   }
21   bool operator<(const employee& e2) const
22   {
23       return this->id < e2.id;
24   }
25 
26   employee& operator=(const employee& e2)
27   {
28       id = e2.id;
29       name = e2.name;
30       age = e2.age;
31       return *this;
32   }
33 
34 };
35 
36 stl::set<employee> set1;
37 
38 set1.insert(employee(2,"Aristotle",23));
39 set1.insert(employee(3,"Albert",20));
40 set1.insert(employee(4,"John",57));
41 
42 set1::iterator it;
43 it = set1.find(employee(3,"Albert",20));   //find参数必须是employee对象,不能只提供id进行查找

 

可以自定义一个带模板的find函数。stl是开源的,可以自己拿出相关代码进行改动,不使用编译库自带的。

 

在stl_set.h中原来的find()函数相同的位置 添加带模板的find函数。

1 //针对属性值的查找接口,需要自定义比较函数。只能在set的当前索引下有序的属性查找,即_T必须是set中有序的属性。stl的find接口只能接受key_type对象作为参数
2       template<class _T, class _T_Compare>
3       const_iterator
4       find(const _T& __x, _T_Compare com)
5       {   return _M_t.find(__x, com);  }

 

在stl_rdtree.h中find()函数相同的位置 添加带模板的find函数,来提供上层set需要调用的接口。

 1     //提供针对属性值的lower_bound接口,使用template
 2     template<class _T, class _T_Compare>
 3     iterator
 4         lower_bound(const _T& __k, _T_Compare com)
 5         {  return _M_lower_bound(_M_begin(), _M_end(), __k, com); }
 6 
 7     //提供针对属性值的查找接口,使用template
 8     template<class _T, class _T_Compare>
 9     const_iterator
10         find(const _T& __k, _T_Compare com) 
11         {
12             const_iterator __j = _M_lower_bound(_M_begin(), _M_end(), __k, com);
13             return (__j == end()
14                     || com(__k, 
15                         _S_key(__j._M_node))) ? end() : __j;
16         }

 

这样就可以使用

     set1::iterator it = set1.find(3);  //查找id为3的对象

posted on 2015-02-12 15:45  呆雁  阅读(452)  评论(0)    收藏  举报

导航