背景:
map的定义
template<class Key, class T, class Pred = less<Key>, class A = allocator<T> >
可见,map的定义是一个模板类,模板参数为Key,T,Pred,A,各参数的含义如下:
Key---------键
T------------值
Pred--------map用于比较键的类,这个类必须重载()操作符,在其中定义比较操作..(虽然比较怪,不是重载大于小于号,但的确是这样定义的)
A------------内存分配
注:由于map是采用了红黑树,而红黑树在操作节点时都需要依赖于比较节点间的大小,所以键采用自定义结构体的条件就是得让系统可以对其进行比较.可以通过两种方法提供这种功能:
1. 为结构体重载<操作符
2. 不需要为结构体重载<操作符.但需要提供一个Pred类,且该类提供了operator()重载.实际上通过class Pred = less<Key>可以看出,map缺省使用系统提供的less类.
以下为两种方案的例子:
1.为自定义类型重载operator<,map的第三个参数为默认仿函数less<key>。
例子:
- #include <iostream>
- #include <map>
- #include <string>
- using namespace std;
- class test
- {
- public :
- bool operator<( const test& a) const ;
- //private:
- int nA;
- int nB;
- };
- bool test::operator<( const test& a) const
- {
- if ( this ->nA < a.nA)
- return true ;
- else
- {
- if ( this ->nA == a.nA && this ->nB < a.nB)
- return true ;
- else
- return false ;
- }
- }
- int main()
- {
- map<test, string> myTestDemo;
- test tA;
- tA.nA = 1;
- tA.nB = 1;
- test tB;
- tB.nA = 1;
- tB.nB = 2;
- myTestDemo.insert(pair<test, string>(tA, "first!" ));
- myTestDemo.insert(pair<test, string>(tB, "second!" ));
- map<test, string>::iterator myItr = myTestDemo.begin();
- cout << "itr begin test nA:" << myItr->first.nA << endl;
- cout << "itr begin test nB:" << myItr->first.nB << endl;
- cout << "itr begin test string:" << myItr->second << endl;
- return 1;
- }
特别注意: operator < 函数的详细内容,一定要满足strict weakly ordering,不能单纯的返回false或true
可以参考:http://www.softwelt.com/Know/KnowDetail-113762.html
2.不使用map的第三个参数为默认仿函数less<key>,自己编写一个比较仿函数。
- #include <iostream>
- #include <map>
- using namespace std;
- struct keyOfMap
- {
- int firstOfKey;
- int secondOfKey;
- };
- struct myMapFunctor
- {
- bool operator()( const keyOfMap& k1, const keyOfMap& k2) const
- {
- if (k1.firstOfKey < k2.firstOfKey)
- return true ;
- else
- return false ;
- }
- };
- int main()
- {
- map<keyOfMap, string, myMapFunctor> test;
- keyOfMap temp1;
- keyOfMap temp2;
- temp1.firstOfKey = 1;
- temp1.secondOfKey = 1;
- temp2.firstOfKey = 2;
- temp2.secondOfKey = 2;
- test.insert(make_pair<keyOfMap, string>(temp1, "first" ));
- test.insert(make_pair<keyOfMap, string>(temp2, "second" ));
- map<keyOfMap, string, myMapFunctor>::iterator begin = test.begin();
- cout << begin->first.firstOfKey << begin->first.secondOfKey << begin->second << endl;
- return 1;
- }