Default sorting and custom sorting for map

Source: Internet
Author: User
Tags custom name

The STL container Map provides a great convenience for us to handle the ordered Key-value form data, and the time complexity of finding is O (log2n) due to the storage of the internal red-black tree structure.

In general, when using map to take the form of Map<typename A, TypeName b>, the internal implementation of map by default uses the type a variable ascending to sort the map value.

But sometimes we need to sort the values of the map in a special order (without the aid of other containers), which requires some special handling when defining the map variable.

The definition of map in STL is:

 1  template<class   _kty,  2  class   _ty,  3  class  _PR = Less<_kty> 4  class  _alloc = Allocator<pair<const  _kty, _ Ty>>>5  class   map  6 : public  _tree<_t Map_traits<_kty, _ty, _PR, _alloc, false  >> 7  {

This is a template class, our special treatment is the main transformation of the class _PR = Less<_kty>, and from here we can see that no matter what kind of modification, the sort is for key , to achieve the value of the custom ordering,

Does not modify the _PR type to complete.

The substitution of _PR must also be a type, that is, at least we have to create a type for ourselves to make a comparison of the key. Naturally, what we need to do is overload the function call operator "()", the general form of

1 class t{2public:3     BOOL operator () (constconst t& RHS)const4    {5         ...     6     }    7 };

The code must include the header file <algorithm>, <functional>.

Here are some of the common custom sorts:

A. Type keys in descending order for basic types

Map By default provides a sort of less<_kty> type, read STL source code

1template<class_ty =void>2     struct Less3{//functor for operator<4 _cxx17_deprecate_adaptor_typedefs typedef _ty FIRST_ARGUMENT_TYPE;5 _cxx17_deprecate_adaptor_typedefs typedef _ty SECOND_ARGUMENT_TYPE;6_cxx17_deprecate_adaptor_typedefs typedefBOOLresult_type;7 8constexprBOOL operator()(Const_ty& _left,Const_ty& _right)Const9{//apply operator< to operandsTen         return(_left <_right); One         } A};

Modifying the 10th line of the above code, a custom name for the modified type is simple, but the STL has provided us with the entire type definition:

1template<class_ty =void>2     structGreater3{//functor for operator>4 _cxx17_deprecate_adaptor_typedefs typedef _ty FIRST_ARGUMENT_TYPE;5 _cxx17_deprecate_adaptor_typedefs typedef _ty SECOND_ARGUMENT_TYPE;6_cxx17_deprecate_adaptor_typedefs typedefBOOLresult_type;7 8constexprBOOL operator()(Const_ty& _left,Const_ty& _right)Const9{//apply operator> to operandsTen         return(_left >_right); One         } A};

We can use it directly:

1std::map<int,int, std::greater<int>>mi;2      for(inti =0; I <5; i++)3     {4Mi[i] = i *2;5     }6 7 Std::for_each (Mi.begin (), Mi.end (),8[](Conststd::map<int,int, std::greater<int>>::value_type&VL) {9cout << "key:" << Vl.first <<"Value:"<< Vl.second <<'\ n';Ten});

The corresponding output is:

  

Here, we have implemented the purpose of descending order by key.

B. Sort the key for the custom type:

When a custom type key defines a map (using the map default sort), we usually do one thing: overloading the "<" operator for a custom type, obviously, this is for map to use less when creating objects.

So we're replacing less<_kty> with the same thing: custom collations, such as:

1 classMyKey {2  Public:3MyKey (intFidx =0,intSidx =0)4 : M_firstidx (FIDX), M_secondidx (SIDX) {}5 6     intM_firstidx;7     intM_secondidx;8 };9 Ten classmycompare{ One  Public: A     BOOL operator()(Constmykey& LHS,Constmykey& RHS)Const -     { -         if(Lhs.m_firstidx >rhs.m_firstidx) the         { -             return true; -         } -         Else if(Lhs.m_firstidx = =rhs.m_firstidx) +         { -             returnLhs.m_secondidx >Rhs.m_secondidx; +         } A         return false; at     } - }; -  - classMyCompare2 { -  Public: -     BOOL operator()(Constmykey& LHS,Constmykey& RHS)Const in     { -         returnLhs.m_firstidx >Rhs.m_firstidx; to     } +};

Using Mycompare:

1Std::map<mykey,int, mycompare>mi;2      for(inti =0; I <5; i++)3     {4Mi[mykey (i *2, i)] = i *2;5     }6 7 Std::for_each (Mi.begin (), Mi.end (),8[](ConstStd::map<mykey,int, mycompare>::value_type&VL) {9cout <<"Key:"<< VL.FIRST.M_FIRSTIDX <<"-"<< VL.FIRST.M_SECONDIDX <<"Value:"<< Vl.second <<'\ n';Ten});

Using MyCompare2:

1Std::map<mykey,int, mycompare2>mi;2      for(inti =0; I <5; i++)3     {4Mi[mykey (i *2, i)] = i *2;5     }6 7 Std::for_each (Mi.begin (), Mi.end (),8[](ConstStd::map<mykey,int, mycompare2>::value_type&VL) {9cout <<"Key:"<< VL.FIRST.M_FIRSTIDX <<"-"<< VL.FIRST.M_SECONDIDX <<"Value:"<< Vl.second <<'\ n';Ten});

Both of the above have the same output:

We implemented custom types to customize the ordering.

As you can see, there is a lot of freedom in using maps, and we can customize our own map to make it easy for us to solve problems and streamline our code.

  

Default sorting and custom sorting for map

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.