当类对象用作映射键时进行排序

时间:2013-06-01 17:12:36

标签: c++ map

我创建了一个包含学生详细信息(名称和ID)的类,我想使用该类的对象作为映射的键值。 我有一些问题

  1. 编译此代码时遇到错误。请告诉我解决方案吗?

  2. 由于地图是有序的,这里我将对象作为键值,它根据键值的排序包含字符串和数字?

  3. 我用过

    cout<<(*ii).first<<'\t'<<(*ii).second<<endl;
    

    打印值。这是打印类对象值的正确方法

    ( (*ii).first)?
    
  4. 请在下面找到我的代码

    #include<iostream>
    #include<map.h>
    #include<utility>
    #include<string.h>
    
    using namespace std;
    
    class A
    {
        private:
        char name[10];
        int id_no;
        public:
        A(char *myname,int no):id_no(no)
        {
            strcpy(name,myname);
        }
        void output()
        {
            cout<<name<<'\t'<<id_no<<endl;
        }
    };     
    
    int main()
    {
        map<A,int> e;
        A a("abc",10);
        A b("xyz",1);
    
        e.insert(pair<A,int>(a,123));
        e.insert(pair<A,int>(b,345));
    
    
        for(map<A,int>::iterator ii = e.begin(); ii!= e.end(); ii++)
        {
            cout<<(*ii).first<<"rank is"<<(*ii).second<<endl;
        }
        return 0;
    }
    

2 个答案:

答案 0 :(得分:2)

  1.   

    编译此代码时出错。

    std::map使用std::less(默认值)来比较密钥。 std::less使用operator<来比较传递的对象。因此,您应该为您的班级重载operator<

    bool operator< (const A& a)
    {
        // compare
    }
    
  2.   

    根据键值进行排序?

    这取决于您的重载operator<

  3.   

    这是打印类对象值的正确方法吗?

    更一般的方法:你应该为operator<<对象和你的类对象重载std::ostream

    friend std::ostream& operator<< (std::ostream& stream, const A& a)
    {
        stream << a.name << '\t' << a.id_no << std::endl;
        return stream;
    }
    

    只有这样你才能打印出来:

    cout << ii -> first << "rank is" << ii -> second << endl;
    

    没有它你应该使用你的output功能:

    ii -> first.output();
    cout << "rank is" << ii -> second << endl;
    

答案 1 :(得分:2)

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

using namespace std;

class A
{
private:
    string name; // there is no reason not using string here
    int id_no;
public:
    A(char *myname, int no) : name(myname), id_no(no)
    {
    }

    void output()
    {
        cout<<name<<'\t'<<id_no<<endl;
    }

    const string & getName() const
    {
        return name;
    }

    bool operator<(const A &right) const // A must be comparable to be used as keys
    {
        return name < right.name;
    }
};     

int main()
{
    map<A,int> e;
    A a("abc",10);
    A b("xyz",1);

    e.insert(pair<A,int>(a,123));
    e.insert(pair<A,int>(b,345));

    for(map<A,int>::iterator ii = e.begin(); ii!= e.end(); ii++)
    {
        cout<<(*ii).first.getName() << " rank is " <<(*ii).second<<endl;
    }
    return 0;
}