// multimaptest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <map>
using namespace std;
struct userdevice{
string m_devicename;
string m_deviceid;
int m_devicePopedom;
};
typedef multimap<string,userdevice> USERTABLE;
typedef USERTABLE::const_iterator CIT;
typedef pair<CIT, CIT> Range;
int _tmain(int argc, _TCHAR* argv[])
{
CIT it;
userdevice d1,d2,d3,d4;
d1.m_deviceid = "12341234";
d1.m_devicename = "d1";
d1.m_devicePopedom = 123;
d2.m_deviceid = "23622344";
d2.m_devicename = "d2";
d2.m_devicePopedom = 234;
d3.m_deviceid = "3451234";
d3.m_devicename = "d3";
d3.m_devicePopedom = 345;
d4.m_deviceid = "43622344";
d4.m_devicename = "d4";
d4.m_devicePopedom = 456;
USERTABLE m_user;
m_user.insert(make_pair("zhangsanfeng",d1));
m_user.insert(make_pair("zhangsanfeng",d2));
m_user.insert(make_pair("zhangsanfeng2",d3));
m_user.insert(make_pair("zhangsanfeng2",d4));
//查找方法一
Range range=m_user.equal_range("zhangsanfeng");
for(CIT i = range.first;i!=range.second;i++)
{
cout << i->second.m_deviceid<<','
<< i->second.m_devicename<<','
<<i->second.m_devicePopedom
<< endl;
}
cout<<endl;
//查找方法二
CIT it2 = m_user.find("zhangsanfeng2");
while(it2 != m_user.end())
{
cout<<it2->second.m_deviceid<<','
<<it2->second.m_devicename<<','
<<it2->second.m_devicePopedom<<','
<<endl;
it2++;
}
cout<<endl;
//遍历
CIT it3 = m_user.begin();
while(it3 != m_user.end())
{
cout<<it3->second.m_deviceid<<','
<<it3->second.m_devicename<<','
<<it3->second.m_devicePopedom<<','
<<endl;
it3++;
}
cin.get();
return 0;
}
lower_bound() 和 upper_bound():lower_bound(k) 查找第一个与键 k 关联的值,而
upper_bound(k) 是查找第一个键值比 k 大的元素。下面的例子示范用
upper_bound()来定位第一个其键值大于“213.108.96.7”的元素。通常,当键是一个字符串时,会有一个词典编纂比较:
dns.insert(make_pair("219.108.96.70", "pythonzone.com"));
CIT cit=dns.upper_bound("213.108.96.7");
if (cit!=dns.end()) //found anything?
cout<<cit->second<<endl; //display: pythonzone.com
如果你想显示其后所有的值,可以用下面这样的循环:
// 插入有相同键的多个值
dns.insert(make_pair("219.108.96.70","pythonzone.com"));
dns.insert(make_pair("219.108.96.70","python-zone.com"));
// 获得第一个值的迭代指针
CIT cit=dns.upper_bound("213.108.96.7");
// 输出: pythonzone.com,python-zone.com
while(cit!=dns.end())
{
cout<<cit->second<<endl;
++cit;
}
结论
虽然 map 和 multimap 具有相同的接口,其重要差别在于重复键,设计和使用要区别对待。此外,还要注意每个容器里 insert()成员函数的细微差别。