【问题标题】:STL--MAP--Adding string as key and class object as valueSTL--MAP--添加字符串作为键和类对象作为值
【发布时间】:2016-04-28 14:44:04
【问题描述】:

代码解释了将对插入到映射中,其中键类型是字符串,值是对类对象的引用。但是,有 3 个重载函数,例如重载 = 运算符、重载

#include <iostream>
    #include <map>
    using namespace std;

    class AAA
    {
       friend ostream &operator<<(ostream &, const AAA &);

       public:
          int x;
          int y;
          float z;

          AAA();
          AAA(const AAA &);
          ~AAA(){};
          AAA &operator=(const AAA &rhs);
          int operator==(const AAA &rhs) const;
          int operator<(const AAA &rhs) const;
    };

    AAA::AAA()   // Constructor
    {
       x = 0;
       y = 0;
       z = 0;
    }

    AAA::AAA(const AAA &copyin)   // Copy constructor to handle pass by value.
    {                             
       x = copyin.x;
       y = copyin.y;
       z = copyin.z;
    }

    ostream &operator<<(ostream &output, const AAA &aaa)
    {
       output << aaa.x << ' ' << aaa.y << ' ' << aaa.z << endl;
       return output;
    }

    AAA& AAA::operator=(const AAA &rhs)
    {
       this->x = rhs.x;
       this->y = rhs.y;
       this->z = rhs.z;
       return *this;
    }

    int AAA::operator==(const AAA &rhs) const
    {
       if( this->x != rhs.x) return 0;
       if( this->y != rhs.y) return 0;
       if( this->z != rhs.z) return 0;
       return 1;
    }

    int AAA::operator<(const AAA &rhs) const
    {
       if( this->x == rhs.x && this->y == rhs.y && this->z < rhs.z) return 1;
       if( this->x == rhs.x && this->y < rhs.y) return 1;
       if( this->x < rhs.x ) return 1;
       return 0;
    }

    main()
    {
       map<string, AAA> M;
       AAA Ablob ;

       Ablob.x=7;
       Ablob.y=2;
       Ablob.z=4.2355;
       M["A"] = Ablob;

       Ablob.x=5;
       M["B"] = Ablob;

       Ablob.z=3.2355;
       M["C"] = Ablob;

       Ablob.x=3;
       Ablob.y=7;
       Ablob.z=7.2355;
       M["D"] = Ablob;

       for( map<string, AAA>::iterator ii=M.begin(); ii!=M.end(); ++ii)
       {
           cout << (*ii).first << ": " << (*ii).second << endl;
       }

       return 0;
    }

【问题讨论】:

    标签: c++ templates dictionary stl


    【解决方案1】:

    它们不是重载,它们是运算符的定义。在这种特殊情况下,复制构造函数和赋值运算符执行默认值的操作,因此应该省略它们。比较运算符应该返回bool 而不是int,并且&lt; 比较可以更有效地编写。给出的代码中没有使用任何比较,因此它们也是多余的。如果 AAA 是地图中的键,那么它们是必要的,但由于它是那里不需要的值。

    顺便说一句,您可以将 for 循环定义为

    for (auto ii = M.begin(); ii != M.end(); ++i)
    

    除非你的编译器足够老以至于它不支持auto的这种用法。

    【讨论】:

    • follow @1201ProgramAlarm 如果 AAA 是关键,那么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-04
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-28
    • 2020-12-12
    相关资源
    最近更新 更多