GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

How to insert an object of in multimap in c++?

suppose my class is 
class student
{
std::string name;
int marks;
};
void main()
{
student st;
multimap<student,int> mymap;
}

how should i insert a class object with other value?

asked Jul 10, 2016 by Confusedtechie

2 Answers

answered Jul 14, 2016 by anonymous

Please make an pair of the object element first and then pair it along with the int  variable with multi set.

Please look the program below

include <iostream>
#include <map>

class student
{
public:
std::string name;
int marks;

};

int main ()
{
    student st;
    student bt;
    st.name = "xyz";
    st.marks = 50;
    bt.name = "abc";
    bt.marks = 75;
    
    std::multimap<std::pair<std::string,int>,int> mymap;
    std::multimap<std::pair<std::string,int>,int>::iterator it;
    
      mymap.insert(std::make_pair(std::make_pair(st.name,st.marks),1));
    mymap.insert(std::make_pair(std::make_pair(bt.name,bt.marks),2));


  // showing contents:
  std::cout << "mymultimap contains:\n";
 for (it=mymap.begin(); it!=mymap.end(); ++it)
    std::cout <<"Name : "<< (*it).first.first<< "Marks:  " << (*it).first.second<< " => " << (*it).second << '\n';

  return 0;
}

answered Jul 15, 2016 by Sunitha Sunagad
...