map以自定义类型当Key

关于map的定义:

template < class Key, class T, class Compare = less<Key>,
           class Allocator = allocator<pair<const Key,T> > > class map;

第一个template参数被当做元素的key,第二个template参数被当作元素的value。Map的元素型别Key和T,必须满足以下两个条件:
1.key/value必须具备assignable(可赋值的)和copyable(可复制的)性质。
2.对排序准则而言,key必须是comparable(可比较的)。
第三个template参数可有可无,用它来定义排序准则。这个排序准则必须定义为strict weak ordering。元素的次序由它们的key决定,和value无关。排序准则也可以用来检查相等性:如果两个元素的key彼此的都不小于对方,则两个元素被视为相等。如果使用未传入特定排序准则,就使用缺省的less排序准则——以operator<来进行比较。

所谓“排序准则”,必须定义strict weak ordering,其意义如下:
1.必须是“反对称性的”。
2.必须是“可传递的”。
3.必须是“非自反的”。

按照定义的要求:
我们有两种方法以自定义类型当key:
1.为自定义类型重载operator<,map的第三个参数为默认仿函数less<key>。

  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. using namespace std;
  5. class test
  6. {
  7. public:
  8. bool operator<(const test& a)const;
  9. //private:
  10. int nA;
  11. int nB;
  12. };
  13. bool test::operator<(const test& a)const
  14. {
  15. if(this->nA < a.nA)
  16. return true;
  17. else
  18.     {
  19. if(this->nA == a.nA && this->nB < a.nB)
  20. return true;
  21. else
  22. return false;
  23.     }
  24. }
  25. int main()
  26. {
  27.     map<test, string> myTestDemo;
  28.     test tA;
  29.     tA.nA = 1;
  30.     tA.nB = 1;
  31.     test tB;
  32.     tB.nA = 1;
  33.     tB.nB = 2;
  34.     myTestDemo.insert(pair<test, string>(tA, "first!"));
  35.     myTestDemo.insert(pair<test, string>(tB, "second!"));
  36.     map<test, string>::iterator myItr = myTestDemo.begin();
  37.     cout << "itr begin test nA:" << myItr->first.nA << endl;
  38.     cout << "itr begin test nB:" << myItr->first.nB << endl;
  39.     cout << "itr begin test string:" << myItr->second << endl;
  40. return 1;
  41. }

2. 不使用map的第三个参数为默认仿函数less<key>,自己编写一个比较仿函数。

    1. #include <iostream>
    2. #include <map>
    3. using namespace std;
    4. struct keyOfMap
    5. {
    6. int firstOfKey;
    7. int secondOfKey;
    8. };
    9. struct myMapFunctor
    10. {
    11. bool operator()(const keyOfMap& k1, const keyOfMap& k2) const
    12.     {
    13. if(k1.firstOfKey < k2.firstOfKey)
    14. return true;
    15. else
    16. return false;
    17.     }
    18. };
    19. int main()
    20. {
    21.     map<keyOfMap, string, myMapFunctor> test;
    22.     keyOfMap temp1;
    23.     keyOfMap temp2;
    24.     temp1.firstOfKey = 1;
    25.     temp1.secondOfKey = 1;
    26.     temp2.firstOfKey = 2;
    27.     temp2.secondOfKey = 2;
    28.     test.insert(make_pair<keyOfMap, string>(temp1, "first"));
    29.     test.insert(make_pair<keyOfMap, string>(temp2, "second"));
    30.     map<keyOfMap, string, myMapFunctor>::iterator begin = test.begin();
    31.     cout << begin->first.firstOfKey << begin->first.secondOfKey << begin->second << endl;
    32. return 1;
原文地址:https://www.cnblogs.com/huhu0013/p/4548543.html