首页 新闻 会员 周边

类定义中的const问题,应用背景为map,求高手解答。。。

0
悬赏园豆:20 [已解决问题] 解决于 2014-02-26 18:00
 1 #include<iostream>
 2 #include<string>
 3 #include<map>
 4 using namespace std;
 5 
 6 /*
 7 通过函数比较器实现map根据值从大到小排列,值相同时根据键从大到小排列
 8 问题在注释中,如果将参数全部定义为const类型则可编译通过
 9 */
10 
11 class String
12 {
13 public:
14     String(const string& s,int i):sval(s),ival(i){}
15     string getVal() const {return sval;}
16     int getIval() const {return ival;}
17     //必须设置成const函数,const函数只能由const函数调用
18     bool operator<(const String& other) const
19     {
20         return ival<other.getIval();
21     }
22 private:
23     string sval;
24     int ival;
25 };
26 
27 //定义比较器类型
28 //编译错误,定义为const则可通过,求详细解释??
29 //typedef const bool (*Comp)(const String& lef,const String& rig);
30 typedef bool (*Comp)(String& lef,String& rig);
31 
32 void print(map<String,int,Comp>& m)
33 {
34     map<String,int,Comp>::iterator iter=m.begin();
35     while(iter!=m.end())
36     {
37         cout<<iter->first.getVal()<<" "<<iter->second<<endl;
38         ++iter;
39     }
40 }
41 
42 //const bool comp(const String& lef,const String& rig)
43 bool comp(String& lef,String& rig)
44 {
45     return (lef.getIval()>rig.getIval())||(lef.getIval()==rig.getIval()&&lef.getVal()>rig.getVal());
46 }
47 
48 int main()
49 {
50     map<String,int,Comp> m(comp);
51     m.insert(make_pair(String("aaa",3),3));
52     m.insert(make_pair(String("ddd",8),8));
53     m[String("bbb",15)]=15;
54     m[String("zzz",15)]=15;
55     print(m);
56 }
leowww的主页 leowww | 初学一级 | 园豆:127
提问于:2014-02-24 16:01
< >
分享
最佳答案
0

typedef bool (*Comp)(String& lef,String& rig);

bool comp(String& lef,String& rig)

要一致。

收获园豆:20
Launcher | 高人七级 |园豆:45045 | 2014-02-24 16:16

不是的,保持一致的前提下,参数一定要设置为const才能通过编译。。。

leowww | 园豆:127 (初学一级) | 2014-02-24 16:39

@leowww: 请看 std::map 的第三个参数的模板:

  // TEMPLATE STRUCT less
template<class _Ty>
 struct less
  : public binary_function<_Ty, _Ty, bool>
 { // functor for operator<
 bool operator()(const _Ty& _Left, const _Ty& _Right) const
  { // apply operator< to operands
  return (_Left < _Right);
  }
 };

要求用于比较大小的参数申明为 const 类型。

Launcher | 园豆:45045 (高人七级) | 2014-02-24 16:54
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册