0

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

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

  2. 由于 map 是有序的,这里我将对象作为键值,它同时具有字符串和数字,基于键值将被排序的内容?

  3. 我用过

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

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

    ( (*ii).first)?
    

请在下面找到我的代码

#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;
}
4

2 回答 2

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;
    
于 2013-06-01T17:20:56.747 回答
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;
}
于 2013-06-01T17:24:37.227 回答