multimap中一個key對應多個鍵值的查詢處理
阿新 • • 發佈:2019-02-08
From:http://zhidao.baidu.com/link?url=s-lktjYYv8TBzqZonvQn0SxGLf7Vgk252-5bNUUxx9wsL_vonx57HvFeN4KN06R3BTc6qOpGWUi2VH7iIH67mMa_ERkAVrIs88cBmdLv8V7
在multimap中,同一個鍵關聯的元素必然相鄰存放。基於這個事實,就可以將某個鍵對應的值一一輸出。
1、使用find和count函式。count函式求出某個鍵出現的次數,find函式返回一個迭代器,指向第一個擁有正在查詢的鍵的例項。
2、使用lower_bound(key)和upper_bound(key)
lower_bound(key)返回一個迭代器,指向鍵不小於k的第一個元素
upper_bound(key)返回一個迭代器,指向鍵不大於k的第一個元素
3、使用equat_range(key)
返回一個迭代器的pair物件,first成員等價於lower_bound(key),second成員等價於upper_bound(key)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
multimap<string, int > m_map;
string s( "中國" ),s1( "美國" );
m_map.insert(make_pair(s,50));
m_map.insert(make_pair(s,55));
m_map.insert(make_pair(s,60));
m_map.insert(make_pair(s1,30)); m_map.insert(make_pair(s1,20));
m_map.insert(make_pair(s1,10));
//方式1
int k;
multimap<string, int >::iterator m;
m = m_map.find(s);
for (k = 0;k != m_map.count(s);k++,m++)
cout<<m->first<< "--" <<m->second<<endl;
//方式2
multimap<string, int >::iterator beg,end;
beg = m_map.lower_bound(s1);
end = m_map.upper_bound(s1);
for (m = beg;m != end;m++)
cout<<m->first<< "--" <<m->second<<endl;
//方式3
beg = m_map.equal_range(s).first;
end = m_map.equal_range(s).second;
for (m = beg;m != end;m++)
cout<<m->first<< "--" <<m->second<<endl;
return 0;
}
|