The classic problem of Sogou interview (map sorted by value)

Source: Internet
Author: User

One: Cause

(1) Java map Sort (key,value), see another blog Java map sort

(2) C + + map ordering (key,value), you can compare C + + map and Java map: one,C + + map By default according to the key value of the order, and is the map ; Java Map HashMap is a

Of the machine , not sorted. The second,C + + declares the object directly to map map (^) without = new

(3) C + + by the value of the order, map is not directly ordered, although it is also a data set, the first reaction is to use the sort algorithm provided in the STL implementation, the idea is good, unfortunately, the sort algorithm

There is a limitation that using the sort algorithm can only sort the sequence container, which is linear (such as Vector,list,deque). map is also a collection container, but the element it stores is pair, it is not

Linear Storage (mentioned earlier, like a red-black tree), so using sort cannot be sorted directly with the map.

Two: Code implementation

(1) First look at the pair class

Template <class T1, class t2> struct pair  {   typedef T1 First_type;   typedef T2 SECOND_TYPE;     T1 first;   T2 second;   Pair (): First (T1 ()), second (T2 ()) {}  pair (const t1& x, const t2& y): First (x), second (y) {}  template & Lt;class U, class v>      pair (const pair<u,v> &p): First (P.first), second (P.second) {}  }
pair is also a template class, so that it achieves a good versatility. It has only two data members first and second, that is , key and value, and

(2) Look at the sort class again

Template <class randomaccessiterator>  void sort (randomaccessiterator first, Randomaccessiterator last);    Template <class Randomaccessiterator, class compare>  

As we can see,it's exciting that thesort algorithm , like map , allows us to specify how the elements are compared, specifying Compare .

(3) Complete code

< Span style= "FONT-SIZE:10.5PT; Font-family: Song body ">

#include <map> #include <string> #include <iostream> #include <vector> #include <algorithm >using namespace Std;typedef pair<string, int> pair;//can also be such overloaded (⊙o⊙) Oh, long to see ostream& operator<< ( ostream& out, const pair& p) {return out << p.first << "\ t" << p.second;} Template<class t1>struct comparebykeylen{//from short to long bool operator (const T1 &s1,const T1 &s2) {R Eturn s1.length () <=s2.length () true:false;//Remember that there is an equal sign oh, otherwise, the length is equal to the}};template<class t1>struct comparebyvalue{bool Operator () (const T1 &AMP;LHS, const T1 &AMP;RHS) {return lhs.second<=rhs.second? tr    Ue:false;    }};int Main () {//map<string, int> name_score_map;//dictionary order, from small to large//default is Map<string,int,less<string>> map<string, int, greater<string> > name_score_map;//note > > with spaces, otherwise cin>>;//dictionary in reverse order, from big to small// map<string, int, comparebykeylen<string> > Name_score_mAp    Self-written comparebykeylen<> structure body map<string, int> name_score_map;    name_score_map["ZhaoBo2"] = 90;    name_score_map["Xuqingzhu"] = 79;    name_score_map["libing"] = 92;    Name_score_map.insert (Make_pair ("Chixiaotong", 99));    Name_score_map.insert (Make_pair ("Wangzhaoxian", 86));    Vector<pair> Name_score_vec (Name_score_map.begin (), Name_score_map.end ());    Sort (Name_score_vec.begin (), Name_score_vec.end (),comparebyvalue<pair> ());    for (int i=0;i<name_score_vec.size (); i++) {cout << name_score_vec[i] << Endl; }//for (map<string, int>::iterator iter = Name_score_map.begin ();//iter! = Name_score_map.end (); + +iter)//{//cout << *iter << endl;//} return 0;}
(4) Operation result:



Three: Sort by key value (c + + map has a comparison class, as in Java, Java also has a similar comparison class)

(1) Compare class own definition

For example, according to the length of the name of students to store, how to do it?

It's very simple, as long as we write a function object ourselves, implement the desired logic, define Map the time to Compare That's what we wrote for ourselves. OK .

Template<class t1>struct comparebykeylen{//from short to long    bool operator (const T1 &s1,const T1 &s2)    {        return S1.length () <=s2.length ()? true:false;//Remember that there is an equal sign, otherwise, the length of the same is Gone    }};

Isn't it simple! Here we do not need to define it as a template, directly specifying that its parameter is a string type is possible.

(2) Reference code

#include <map> #include <string> #include <iostream>using namespace std;typedef pair<string, int > pair;//original can also be such overloaded (⊙o⊙) Oh, long Insight ostream& operator<< (ostream& out, const pair& p) {return out <& Lt P.first << "\ t" << p.second;} Template<class t1>struct comparebykeylen{//from short to long bool operator (const T1 &s1,const T1 &s2) {R Eturn s1.length () <=s2.length () true:false;//Remember the equals sign Oh, otherwise, the length is equal to the}};int main () {//map<string, int> name_sc ore_map;//dictionary order, from small to large//default is map<string,int,less<string>>//map<string, int, greater<string> ; name_score_map;//Note > > There are spaces, otherwise cin>>;//dictionary in reverse order, from large to small map<string, int, Comparebykeylen > Name_score_m    Ap    name_score_map["Zhaobo"] = 90;    name_score_map["Xuqingzhu"] = 79;    name_score_map["libing"] = 92;    Name_score_map.insert (Make_pair ("Chixiaotong", 99));    Name_score_map.insert (Make_pair ("Wangzhaoxian", 86)); for (map&Lt;string, Int>::iterator iter = Name_score_map.begin ();    Iter! = Name_score_map.end (); ++iter) {cout << *iter << Endl; } return 0;}

(3) Operation result


This is a little bit like Java of the Map but it's not the same, it feels Java It's a bit of a hassle.



The classic problem of Sogou interview (map sorted by value)

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.