A programmer writing C++ multimap program.

C++ multimap Example

  • C++
  • 2 mins read

In this tutorial, we will see a C++ multimap example to find a value in a map with duplicate key values.

C++ Header Files for multimap Program

#include <iostream>
#include <map>
#include <vector>
#include <iterator>
#include <algorithm>

multimap Initialization in C++

 multimap< string, long > contacts = {

	    { "V.Jegan", 2232342323  },
	    { "R.Meena", 3243435323  },
	    { "V.Nitesh",6234324323  },
	    { "S.Sriram",8932443221  },
	    { "V.Nitesh",5534327326  }

    };

Finding a Key in multimap

auto pos  = contacts.find ( "V.Nitesh" );

Iterating in multimap

while ( pos != contacts.end() ) { 
	    cout << "\nMobile number of " << pos->first << " is " << pos->second << endl;
    	    ++pos;
    }

Complete C++ multimap Example

In the following example, it will find the key V.Nitesh and will print the contact number if found.

#include <iostream>
#include <map>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;

int main( ) {

    multimap< string, long > contacts = {

	    { "V.Jegan", 2232342323  },
	    { "R.Meena", 3243435323  },
	    { "V.Nitesh",6234324323  },
	    { "S.Sriram",8932443221  },
	    { "V.Nitesh",5534327326  }

    };

    auto pos  = contacts.find ( "V.Nitesh" );
    int count = contacts.count( "V.Nitesh" );
    int index = 0;

    while ( pos != contacts.end() ) {
	    cout << "\nMobile number of " << pos->first << " is " << pos->second << endl;
	    ++index;
	    if ( index == count ) 
		break;
    }

    cout << "--------------------------------------------------------------" << endl;

    pos = contacts.begin();

    while ( pos != contacts.end() ) { 
	    cout << "\nMobile number of " << pos->first << " is " << pos->second << endl;
    	    ++pos;
    }


    return 0;
}

Output

Mobile number of V.Nitesh is 6234324323

Mobile number of V.Nitesh is 6234324323
--------------------------------------------------------------

Mobile number of R.Meena is 3243435323

Mobile number of S.Sriram is 8932443221

Mobile number of V.Jegan is 2232342323

Mobile number of V.Nitesh is 6234324323

Mobile number of V.Nitesh is 5534327326