乐趣区

关于c++:C-STL-multimap容器

一、前言

multimap 容器和 map 容器根本相似,在这里只阐明 map 容器没有的内容,或者与 map 容器的区别。
和 map 容器的区别在于:multimap 容器中能够同时存储多(≥2)个键雷同的键值对。

二、办法

和 map 容器相比,multimap 未提供 at() 成员办法,也没有重载 [] 运算符。因而这里说一下 multimap 容器获取值的办法。

1、获取值

1)办法 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)办法 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)办法 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;}

后果如下:

退出移动版