如何显示存储在multimap中的类数据成员

时间:2016-07-11 11:00:13

标签: c++ stl multimap

这是代码

class student
{
int num;
string name;
float marks;
public:
void add()
{
    cout << "Enter the num name and marks:" << endl;
    cin >> num >> name >> marks;
}
void display()
{
    cout << num << endl;
    cout << name << endl;
    cout << marks << endl;
}
};
void main()
{
student ss;
multimap<int,student> st;
multimap<int,student>::iterator itr;
    ss.add();
    st.insert(make_pair(1000, ss));

for (itr = st.begin(); itr != st.end(); itr++)
{
    cout << itr->second; // its showing ERROR 
}
}

错误是 错误C2679二进制&#39;&lt;&lt;&#39;:找不到运算符,该运算符采用类型&#39; student&#39;的右手操作数。 (或者没有可接受的转换)firstmultimap
如何解决这个问题

1 个答案:

答案 0 :(得分:0)

要显示学生对象,您需要重载<<运算符。

我已经使student类的操作符重载函数友好,因此可以在不创建对象的情况下调用它。

另外,请在MSDN上查看此示例。

示例:

#include<iostream>
#include<map>
#include<string>
using namespace std;
class student
{
private:
    int num;
    string name;
    float marks;
public:
    void add()
    {
        cout << "Enter the num name and marks:" << endl;
        cin >> num >> name >> marks;
    }
    void display()
    {
        cout << num << endl;
        cout << name << endl;
        cout << marks << endl;
    }
    friend ostream &operator << (ostream &output, const student &s)
    {
        output << "Num: " << s.num << "\nName: " << s.name << "\nMarks: " << s.marks << endl;
        return output;
    }
};

int main()
{
    student ss;
    multimap<int, student> st;
    multimap<int, student>::iterator itr;
    ss.add();
    st.insert(make_pair(1000, ss));
    for (itr = st.begin(); itr != st.end(); itr++)
    {
        cout << itr->second;
    }
    // Using Range based for loop
    // for(const auto &i : st)
    //     cout << i.second;
    return 0;
}