C ++ map custom sorting rules

Source: Internet
Author: User

The template of map defines the third parameter, that is, our sorting rule.

STD: less <> is used by default to sort keys instead of values.

If we want to sort the key (string) in case-insensitive order, we can write it like this.


# Include "stdafx. H "# include <cctype> # include <map> # include <algorithm> # include <string> # include <iostream> using namespace STD; // provides custom sorting struct ccaseinsensitive {bool operator () (const string & str1, const string & str2) const {string str1nocase (str1); string str2nocase (str2 ); transform (str1.begin (), str1.end (), str1nocase. begin (), tolower); transform (str2.begin (), str2.end (), str2nocase. begin (), tolower); Return str1nocase <str2nocase; }}; // defines strmapnocasetypedef Map <string, String, ccaseinsensitive> strmapnocase; typedef strmapnocase: value_type mapvalue; typedef Map <string, string> strmap; int main () {strmapnocase map1; map1.insert (mapvalue ("John", "5214563"); map1.insert (mapvalue ("Tom", "5214563 ")); map1.insert (mapvalue ("Liyang", "98874745"); map1.insert (mapvalue ("ABC", "98874745"); strmap MAP2; map2. I Nsert (mapvalue ("John", "5214563"); map2.insert (mapvalue ("Tom", "5214563"); map2.insert (mapvalue ("Liyang ", "98874745"); map2.insert (mapvalue ("ABC", "98874745"); strmapnocase: iterator iter1 = map1.find ("ABC"); If (iter1! = Map1.end () cout <(* iter1). First <Endl; strmap: iterator iter2 = map2.find ("ABC"); If (iter2! = Map2.end () cout <(* iter2 ). first <Endl; elsecout <"ABC" not found in MAP2 <Endl; System ("pause"); Return 0 ;}


Running result:

ABC

ABC not found in MAP2


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.