C++ STL Multimap container

Time:2022-5-31

1、 Foreword

The Multimap container is basically similar to the map container. Here, only the contents that the map container does not have or the differences between the Multimap container and the map container are explained.
The difference from the map container is that multiple key value pairs with the same key (≥ 2) can be stored in the Multimap container at the same time.

2、 Method

Compared with the map container, Multimap does not provide at () member methods, nor does it overload [] operators. So let’s talk about how the Multimap container gets values.

1. Get value

1) Method 1

std::multimap<int, string> multimap{ {1,"lin"},{1,"wen"},{1, "kai"},{2,"li"},{2,"wu"},{3,"huang"} };
    
int nCount = multimap.count(1);
std::cout << "nCount: " << nCount << std::endl;

std::multimap<int, string>::iterator mtmapIter = multimap.begin();
for (int i = 0; i < nCount; i++)
{
    std::cout << mtmapIter->first << "  " << mtmapIter->second << std::endl;
    ++mtmapIter;
}

2) Method 2

std::multimap<int, string> multimap{ {1,"lin"},{1,"wen"},{1, "kai"},{2,"li"},{2,"wu"},{3,"huang"} };
    
int nCount = multimap.count(1);
std::cout << "nCount: " << nCount << std::endl;
std::multimap<int, string>::iterator mtmapBeginIter = multimap.lower_bound(1);

for (; mtmapBeginIter != multimap.upper_bound(1); mtmapBeginIter++)
{
    std::cout << mtmapBeginIter->first << "  " << mtmapBeginIter->second << std::endl;
}

3) Method 3

std::multimap<int, string> multimap{ {1,"lin"},{1,"wen"},{1, "kai"},{2,"li"},{2,"wu"},{3,"huang"} };
    
int nCount = multimap.count(1);
std::cout << "nCount: " << nCount << std::endl;
pair<std::multimap<int, string>::iterator, std::multimap<int, string>::iterator> iter = multimap.equal_range(1);

for (; iter.first != iter.second; iter.first++)
{
    std::cout << iter.first->first << "  " << iter.first->second << std::endl;
}

The results are as follows:
C++ STL Multimap container