multimap
- Multiple elements can have equivalent keys
- Elements are sorted by its key following a specific order indicated by its comparison object
- Implemented as a balanced binary search tree
Initialization
#include <iostream>
#include <map>
#include <string>
template <class T>
void display(T it, T end)
{
while(it != end)
{
std::cout<<it->first<<" "<<it->second<<std::endl;
std::advance(it, 1);
}
}
int main(int argc, char *argv[])
{
std::multimap<std::string, std::string> m;
m.insert(std::make_pair("Buick", "Centry"));
m.insert(std::make_pair("Buick", "Rendezvous"));
display(m.begin(), m.end());
return 0;
}
Access Elements
#include <iostream>
#include <map>
#include <string>
template <class T>
void display(T it, T end)
{
while(it != end)
{
std::cout<<it->first<<" "<<it->second<<std::endl;
std::advance(it, 1);
}
}
int main(int argc, char *argv[])
{
std::multimap<std::string, std::string> m;
m.insert(std::make_pair("Buick", "Centry"));
m.insert(std::make_pair("Buick", "Rendezvous"));
m.insert(std::make_pair("Honda", "CRV"));
m.insert(std::make_pair("Honda", "Accord"));
//equal_range
auto ret = m.equal_range("Honda");
for(auto it = ret.first; it != ret.second; ++it)
std::cout<<it->second<<std::endl;
return 0;
}
Find and Erase
#include <iostream>
#include <map>
#include <string>
template <class T>
void display(T it, T end)
{
while(it != end)
{
std::cout<<it->first<<" "<<it->second<<std::endl;
std::advance(it, 1);
}
}
int main(int argc, char *argv[])
{
std::multimap<std::string, std::string> m;
m.insert(std::make_pair("Buick", "Centry"));
m.insert(std::make_pair("Buick", "Rendezvous"));
m.insert(std::make_pair("Honda", "CRV"));
m.insert(std::make_pair("Honda", "Accord"));
//find
auto it = m.find("Honda");
std::cout<<it->first<<" "<<it->second<<std::endl;//Honda CRV
//erase
m.erase(it);
display(m.begin(), m.end());
return 0;
}
Multimap with Objects
#include <iostream>
#include <map>
#include "Rectangle.h"
struct comp{
bool operator()(const Rectangle &a, const Rectangle &b)
{
return (a.getArea() < b.getArea());
}
};
template <class T>
void display(T it, T end)
{
while(it != end)
{
std::cout<<it->first.getArea()<<std::endl;
std::advance(it, 1);
}
}
int main(int argc, char *argv[])
{
std::multimap<Rectangle, int, comp> m;
Rectangle r1(1, 2);
Rectangle r2(1, 2);
Rectangle r3(2, 3);
Rectangle r4(2, 4);
m.insert(std::make_pair(r1, 1));
m.insert(std::make_pair(r2, 2));
m.insert(std::make_pair(r3, 3));
m.insert(std::make_pair(r4, 4));
Rectangle r5(1, 2);
auto it = m.find(r5);
std::cout<<it->first.getArea()<<std::endl;//2
display(m.begin(), m.end());
return 0;
}
Reference