// 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()成員函數的細微差別。