#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;
}