#include <map>
#include <iostream>
using namespace std;
void test_multimap()
{
//构造 multimap 的测试数据
multimap<string, string> example;
example.insert(make_pair(string("A"), string("11")));
example.insert(make_pair(string("A"), string("22")));
example.insert(make_pair(string("A"), string("33")));
example.insert(make_pair(string("B"), string("44")));
example.insert(make_pair(string("B"), string("55")));
example.insert(make_pair(string("B"), string("66")));
example.insert(make_pair(string("C"), string("77")));
example.insert(make_pair(string("C"), string("88")));
example.insert(make_pair(string("C"), string("99")));
example.insert(make_pair(string("D"), string("000")));
example.insert(make_pair(string("D"), string("111")));
example.insert(make_pair(string("D"), string("222")));
example.insert(make_pair(string("F"), string("0000")));
example.insert(make_pair(string("F"), string("1111")));
example.insert(make_pair(string("F"), string("2222")));
example.insert(make_pair(string("F"), string("3333")));
std::string del_item("A");
multimap<string, string>::size_type count = example.erase(del_item);
std::string search_item = "C";
multimap<string, string>::iterator iter = example.find(search_item);
multimap<string, string>::size_type all = example.count(search_item);
//采用指定数量遍历
for (multimap<string, string>::size_type cnt = 0; cnt < all; ++cnt, ++iter)
{
std::cout << iter->first << ":" << iter->second << endl;
}
//采用一个指定范围的迭代器遍历
search_item = "B";
for (iter = example.lower_bound(search_item); iter != example.upper_bound(search_item); ++iter)
{
std::cout << iter->first << ":" << iter->second << endl;
}
//使用成对迭代器来遍历元素
search_item = "D";
pair<multimap<string, string>::iterator, multimap<string, string>::iterator> pos;
for (pos = example.equal_range(search_item); pos.first != pos.second; ++pos.first)
{
std::cout << pos.first->first << ":" << pos.first->second << endl;
}
//multimap 中删除元素
search_item = "F";
for (iter = example.begin(); iter != example.end();)
{
if (iter->second == "0000" || iter->second == "2222")
{
std::cout << "erase " << iter->first << ":" << iter->second << endl;
example.erase(iter++);
}
else
{
iter++;
}
}
//输出所有元素
for (iter = example.begin(); iter != example.end(); ++iter)
{
std::cout << iter->first << ":" << iter->second << endl;
}
//查看multimap 的帮助文件,没有看到 multimap::operator[] 的定义,所以应该不支持
//这个访问方式,就算支持,也不好定义其返回的值,比如 map 是这样定义的
//Type& operator[](const Key& _Key);multimap 不好定义
}
int main(int argc, char *argv[])
{
test_multimap();
return 0;
}