鱼C论坛

 找回密码
 立即注册
查看: 2499|回复: 3

map

[复制链接]
发表于 2012-2-11 19:41:23 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <iostream>
#include <map>
using namespace std;
class A
{
        private:
        int a;
        public:
        A(int _a):a(_a){}
        bool operator >(A s)
        {
                return (this->a>s.a);
        }
        void show()
        {
                cout<<"a="<<a<<endl;
        }
};
class B
{
        public:
        bool operator () (A a,A b)
        {
                return (a>b);
        }
};
void display(map<A,int,B> s)
{
        map<A,int,B>::iterator it;
        for(it=s.begin();it!=s.end();it++)
        {
                //(it->first).show();
        }
}

int main()
{
        map<A,int,B> c1;
        c1.insert(map<A,int,B>::value_type(A(1),1));
        c1.insert(pair<A,int>(A(2),2));
        display(c1);
        return 0;
}

编译报错,请求帮助
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
发表于 2012-2-11 21:33:24 | 显示全部楼层
已回答,见你的另一帖子。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
 楼主| 发表于 2012-2-13 15:19:49 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
发表于 2012-2-14 19:06:48 | 显示全部楼层
  1. #include <iostream>
  2. #include <map>
  3. using namespace std;
  4. class A
  5. {
  6.         private:
  7.         int a;
  8.         public:
  9.         A(int _a):a(_a){}
  10.         bool operator >(A s)
  11.         {
  12.                 return (this->a>s.a);
  13.         }
  14.         void show() const
  15.         {
  16.                 cout<<"a="<<a<<endl;
  17.         }
  18. };
  19. class B
  20. {
  21.         public:
  22.         bool operator () (A a,A b)
  23.         {
  24.                 return (a>b);
  25.         }
  26. };
  27. void display(map<A,int,B> s)
  28. {
  29.         map<A,int,B>::iterator it;
  30.         for(it=s.begin();it!=s.end();it++)
  31.         {
  32.                 (it->first).show();
  33.         }
  34. }

  35. int main()
  36. {
  37.         map<A,int,B> c1;
  38.         c1.insert(map<A,int,B>::value_type(A(1),1));
  39.         c1.insert(pair<A,int>(A(2),2));
  40.         display(c1);
  41.         return 0;
  42. }
复制代码
把成员函数show写为const成员函数,因为map容器的每个元素pair里,first成员都是const类型的,因此只能调用const成员函数
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 18:20

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表