如果鍵值是string型,直接輸出就可以了,multimap是排好序了的,如果你要用C風格字符串,就自定義一個排序規則,需要在創建 multimap的時候做:
#include <map>
#include <iostream>
#include <cstring>
using namespace std;
struct cstrcmp_less
{
bool operator () (const char* a, const char* b)
{
return strcmp(a, b) == -1 ? 1 : 0;
}
};
int main()
{
multimap<const char*, const char*, cstrcmp_less> xx;
xx.insert(make_pair("12","22"));
xx.insert(make_pair("23","22"));
xx.insert(make_pair("14","22"));
xx.insert(make_pair("11","22"));
for(multimap<const char*, const char*>::iterator it = xx.begin(); it != xx.end(); ++it)
cout << it->first << endl;
}
C++ STL中標準關聯容器set, multiset, map, multimap內部採用的就是一種非常高效的平衡檢索二叉樹:紅黑樹,也成爲RB樹(Red-Black Tree)。
map和set的樹建立之時就會自動排好序,之前使用map,覺得按value排序很麻煩,要建一個multimap將原map倒置存儲。如何只用一個map實現value的排序呢?將key 和 value建一個結構體,再將結構體作爲key建一個map。
而排序當然要寫比較函數,這個又如何解決呢?之前沒去想map構造map<T1, T2>時,其實是有個默認的比較函數 map<T1, T2, less<T1>> ,即按key的升序排列,我們可以重寫比較函數來實現我們想要的排序(value)。假設string是key, int是value;
代碼如下:
#include<iostream>
#include<map>
#include<string>
using namespace std;
struct A
{
string s;
int n;
};
class KeyComp
{
public:
bool operator()(const A& a1, const A& a2) const
{
return (a1.n < a2.n ||(a1.n == a2.n && a1.s < a2.s));
}
};
int main()
{
map<A, int, KeyComp> m;
map<A, int, KeyComp>::iterator it;
A rec;
while(cin >> rec.s >> rec.n)
{
m[rec]++;
}
for(it = m.begin(); it != m.end(); it++)
{
cout << it->first.s << " " << it->first.n << " " << it->second;
cout << endl;
}
return 0;
}
#include<iostream>
#include<map>
#include<string>
using namespace std;
struct A
{
string s;
int n;
};
class KeyComp
{
public:
bool operator()(const A& a1, const A& a2) const
{
return (a1.n < a2.n ||(a1.n == a2.n && a1.s < a2.s));
}
};
int main()
{
map<A, int, KeyComp> m;
map<A, int, KeyComp>::iterator it;
A rec;
while(cin >> rec.s >> rec.n)
{
m[rec]++;
}
for(it = m.begin(); it != m.end(); it++)
{
cout << it->first.s << " " << it->first.n << " " << it->second;
cout << endl;
}
return 0;
}