c++ - how to display class data members stored in multimap -
here code
class student { int num; string name; float marks; public: void add() { cout << "enter num name , 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)); (itr = st.begin(); itr != st.end(); itr++) { cout << itr->second; // showing error } }
the error error c2679 binary '<<': no operator found takes right-hand operand of type 'student' (or there no acceptable conversion) firstmultimap
how fix this
to display student object need overload <<
operator.
i have made operator overloading function friend of student
class called without creating object.
also, check example on msdn.
example:
#include<iostream> #include<map> #include<string> using namespace std; class student { private: int num; string name; float marks; public: void add() { cout << "enter num name , 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)); (itr = st.begin(); itr != st.end(); itr++) { cout << itr->second; } // using range based loop // for(const auto &i : st) // cout << i.second; return 0; }
Comments
Post a Comment