C++ Program to Implement Multimap in STL

«
»
This C++ Program demonstrates the implementation of Multimap in STL.

Here is source code of the C++ Program to implement Multimap in STL. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Implement Multimap in STL
  3.  */
  4. #include <iostream>
  5. #include <map>
  6. #include <string>
  7. using namespace std;
  8. int main ()
  9. {
  10.     multimap<char, int> mymm;
  11.     multimap<char, int>::iterator it;
  12.     mymm.insert (pair<char, int>('x', 100));
  13.     mymm.insert (pair<char, int>('y', 200));
  14.     mymm.insert (pair<char, int>('y', 300));
  15.     mymm.insert (pair<char, int>('y', 400));
  16.     mymm.insert (pair<char, int>('z', 500));
  17.     mymm.insert (pair<char, int>('z', 500));
  18.     cout<<"Size of the multimap: "<< mymm.size() <<endl;
  19.     cout << "Multimap contains:\n";
  20.     for (it = mymm.begin(); it != mymm.end(); ++it)
  21.         cout << (*it).first << " => " << (*it).second << '\n';
  22.     for (char c = 'x'; c <= 'z'; c++)
  23.     {
  24.         cout << "There are " << mymm.count(c) << " elements with key " << c << ":";
  25.         multimap<char, int>::iterator it;
  26.         for (it = mymm.equal_range(c).first; it != mymm.equal_range(c).second; ++it)
  27.             cout << ' ' << (*it).second;
  28.         cout << endl;
  29.     }
  30.     it = mymm.find('x');
  31.     mymm.erase (it);
  32.     cout<<"Size of the multimap: "<<mymm.size()<<endl;
  33.     // showing contents:
  34.     cout << "Multimap contains:\n";
  35.     for (it = mymm.begin(); it != mymm.end(); ++it)
  36.         cout << (*it).first << " => " << (*it).second << '\n';
  37.     return 0;
  38. }

advertisement
$ g++ multimap_stl.cpp
$ a.out
 
Size of the multimap: 6
Multimap contains:
x => 100
y => 200
y => 300
y => 400
z => 500
z => 500
There are 1 elements with key x: 100
There are 3 elements with key y: 200 300 400
There are 2 elements with key z: 500 500
Size of the multimap: 5
Multimap contains:
y => 200
y => 300
y => 400
z => 500
z => 500
 
------------------
(program exited with code: 1)
Press return to continue

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn