Home Database Mysql Tutorial 由2个值组合成key的STL map排序问题

由2个值组合成key的STL map排序问题

Jun 07, 2016 pm 03:08 PM
key map stl synthesis sort question

在C中,map是典型的关联容器或者叫映射容器(associative container),其中的每一个元素都是由key-value这样成对出现的内容组成的,比如学号和学生之类具有一一对应关系的情形,学号可以作为key,学生对象可以作为key所对应的value。很显然这种情况下的key只

在C++中,map是典型的关联容器或者叫映射容器(associative container),其中的每一个元素都是由key-value这样成对出现的内容组成的,比如学号和学生之类具有一一对应关系的情形,学号可以作为key,学生对象可以作为key所对应的value。很显然这种情况下的key只有一个值,但是,在实际工作中,我们可能会经常需要使用多个值组合起来作为key的情况,比如我们要按照学生的视力和身高进行排序,以决定学生的座位排在前面还是后面,而且还是假定要用map来解决这样的问题(当然,这样的问题有很多其它的解决办法),那应该怎么办呢?

 

(1)  单值作为key的情形

我们知道map在缺省状态下,其数据是按照key的升序进行排列的。假定我们有一个Student类,声明如下:

[cpp] view plaincopy

  1. class Student  
  2. {  
  3. private:  
  4.          int id;                  // 学号  
  5.          string name;             // 姓名  
  6.          float eyesight;          // 视力  
  7.          float height;            // 身高  
  8.          float chinese;           // 语文成绩  
  9.          float english;           // 英文成绩  
  10.          float math;              // 数学成绩  
  11. public:  
  12.          Student(int id, string name,floateyesight, float height,float chinese, float english,float math)  
  13.          {  
  14.                    this->id = id;  
  15.                    this->name = name;  
  16.                    this->eyesight = eyesight;  
  17.                    this->height = height;  
  18.                    this->chinese = chinese;  
  19.                    this->english = english;  
  20.                    this->math = math;  
  21.          }  
  22.    
  23.          int get_id()  
  24.          {  
  25.                    return id;  
  26.          }  
  27.    
  28.          string get_name()  
  29.          {  
  30.                    return name;  
  31.          }  
  32.    
  33.          float get_eyesight()  
  34.          {  
  35.                    return eyesight;  
  36.          }  
  37.    
  38.          float get_height()  
  39.          {  
  40.                    return height;  
  41.          }  
  42.    
  43.          float get_chinese()  
  44.          {  
  45.                    return chinese;  
  46.          }  
  47.    
  48.          float get_english()  
  49.          {  
  50.                    return english;  
  51.          }  
  52.    
  53.          float get_math()  
  54.          {  
  55.                    return math;  
  56.          }  
  57. };  
 

那么下面的程序:

[cpp] view plaincopy

  1. int main(int argc,char**argv)  
  2. {  
  3.        mapint, Student> stu_map;    // int作为key的类型,Student作为value的类型  
  4.        stu_map.insert(make_pair(4,Student(4, "Dudley",1.1f, 170.2f, 90.5f, 89.5f, 93.0)));  
  5.        stu_map.insert(make_pair(3,Student(3, "Chris", 1.1f, 163.4f, 93.5f,90.0f, 83.5f)));  
  6.        stu_map.insert(make_pair(2,Student(2, "Bob", 1.5f, 166.6f, 86.0f,98.5f, 85.0f)));  
  7.        stu_map.insert(make_pair(1,Student(1, "Andrew", 1.5f, 173.2f, 98.5f,100.0f, 100.f)));  
  8.    
  9.        mapint, Student>::iterator iter;  
  10.        for(iter = stu_map.begin(); iter != stu_map.end();++iter)  
  11.        {  
  12.               coutfirst "\t"second.get_name() 
  13.        }  
  14.    
  15.        return 0;  
  16. }  
 

就会按照学号的升序给出输出:

1          Andrew

2          Bob

3          Chris

4          Dudley

这是缺省的情形,如果要将学生的姓名按照学号的降序输出,那么仅需将上面main函数中的

mapint,Student> stu_map;改为

mapint,Student, greaterint> > stu_map;

以及

mapint,Student>::iterator iter;改为

mapint,Student, greaterint> >::iteratoriter;

即可。

 

其实,mapint,Student> stu_map;这是一种缺省的情况,它和

mapint,Student, lessint> > stu_map;是一样的。

 

(2) 多值组合作为key的情形

现在,我们来看看多个值组合起来作为key的情况,为此,我们需要为key定义一个类,如下:

[cpp] view plaincopy

  1. class key  
  2. {  
  3. public:  
  4.        float eyesight;  
  5.        float height;  
  6.    
  7.        key(float x, floaty):eyesight(x), height(y)  
  8.        {  
  9.        }  
  10.    
  11.        friend bool operator const key&);  
  12. };  
  13.    
  14. bool operator const key& key2)  
  15. {  
  16.        // 按eyesight升序 + height升序排列  
  17.        if(key1.eyesight != key2.eyesight)        
  18.               return (key1.eyesight 
  19.        else  
  20.               return (key1.height 
  21.         
  22.        // 按eyesight降序 + height降序排列  
  23.        //if(key1.eyesight != key2.eyesight)      
  24.        //     return(key1.eyesight > key2.eyesight);  
  25.        //else                                   
  26.        //     return(key1.height > key2.height);  
  27.    
  28.        // 按eyesight升序 + height降序排列  
  29.        //if(key1.eyesight != key2.eyesight)      
  30.        //     return(key1.eyesight   
  31.        //else                                   
  32.        //     return(key1.height > key2.height);  
  33.    
  34.        // 按eyesight降序 + height升序排列  
  35.        //if(key1.eyesight != key2.eyesight)      
  36.        //     return(key1.eyesight > key2.eyesight);  
  37.        //else                                   
  38.        //     return(key1.height   
  39. }  
 

再修改main函数如下:

[cpp] view plaincopy

  1. int main(int argc,char**argv)  
  2. {  
  3.        map stu_map;  
  4.    
  5.        Studentstu4(4, "Dudley",1.1f, 170.2f, 90.5f, 89.5f, 93.0);  
  6.        Studentstu3(3, "Chris", 1.1f, 163.4f, 93.5f,90.0f, 83.5f);  
  7.        Studentstu2(2, "Bob", 1.5f, 166.6f, 86.0f,98.5f, 85.0f);  
  8.        Studentstu1(1, "Andrew", 1.5f, 173.2f, 98.5f,100.0f, 100.f);  
  9.    
  10.        stu_map.insert(make_pair(key(stu4.get_eyesight(),stu4.get_height()), stu4));  
  11.        stu_map.insert(make_pair(key(stu3.get_eyesight(),stu3.get_height()), stu3));  
  12.        stu_map.insert(make_pair(key(stu2.get_eyesight(),stu2.get_height()), stu2));  
  13.        stu_map.insert(make_pair(key(stu1.get_eyesight(),stu1.get_height()), stu1));  
  14.    
  15.        map::iterator iter;  
  16.        for(iter = stu_map.begin(); iter != stu_map.end();++iter)  
  17.        {  
  18.              coutfirst.eyesight "\t"first.height  "\t" second.get_id()"\t" second.get_name() 
  19.        }  
  20.    
  21.        return 0;  
  22. }  

那么输出结果为:

1.1    163.4        3       Chris

1.1    170.2        4       Dudley

1.5    166.6        2       Bob

1.5    173.2        1       Andrew

从上面的输出,我们可以很明显地看到,是按照视力升序和升高升序输出的,另外三种可能的排序情况,也在类key的操作符“

 

(3)结论

1.通常我们不用STL algorithm中的sort函数,来对一个map进行排序,而对vector的元素进行排序则可以很方面地使用sort函数;

2.多值组合作为key的情况,需要我们自己定义一个key类,并在该类中重载操作符“


附两个值作为key的情况之完整的实验代码如下:

[cpp] view plaincopy

  1. #include   
  2. #include   
  3. #include   
  4. using namespace std;   
  5.    
  6. class key  
  7. {  
  8. public:  
  9.        float eyesight;  
  10.        float height;  
  11.    
  12.        key(float x, floaty):eyesight(x), height(y)  
  13.        {  
  14.        }  
  15.    
  16.        friend bool operator const key&);  
  17. };  
  18.    
  19. bool operator const key& key2)  
  20. {  
  21.        // 按eyesight升序 + height升序排列  
  22.        if(key1.eyesight != key2.eyesight)        
  23.               return (key1.eyesight 
  24.        else  
  25.               return (key1.height 
  26.         
  27.        // 按eyesight降序 + height降序排列  
  28.        //if(key1.eyesight != key2.eyesight)      
  29.        //     return(key1.eyesight > key2.eyesight);  
  30.        //else                                   
  31.        //     return(key1.height > key2.height);  
  32.    
  33.        // 按eyesight升序 + height降序排列  
  34.        //if(key1.eyesight != key2.eyesight)      
  35.        //     return(key1.eyesight   
  36.        //else                                   
  37.        //     return(key1.height > key2.height);  
  38.    
  39.        // 按eyesight降序 + height升序排列  
  40.        //if(key1.eyesight != key2.eyesight)      
  41.        //     return(key1.eyesight > key2.eyesight);  
  42.        //else                                   
  43.        //     return(key1.height   
  44. }  
  45.    
  46. class Student  
  47. {  
  48. private:  
  49.          int id;                   //学号  
  50.          string name;              // 姓名  
  51.          float eyesight;           //视力  
  52.          float height;             //身高  
  53.          float chinese;            //语文成绩  
  54.          float english;            //英文成绩  
  55.          float math;               //数学成绩  
  56. public:  
  57.        Student(int id, string name,floateyesight,float height,float chinese,float english,float math)  
  58.        {  
  59.               this->id = id;  
  60.               this->name = name;  
  61.               this->eyesight = eyesight;  
  62.               this->height = height;  
  63.               this->chinese = chinese;  
  64.               this->english = english;  
  65.               this->math = math;  
  66.        }  
  67.    
  68.        int get_id()  
  69.        {  
  70.               return id;  
  71.        }  
  72.    
  73.        string get_name()  
  74.        {  
  75.               return name;  
  76.        }  
  77.    
  78.        float get_eyesight()  
  79.        {  
  80.               return eyesight;  
  81.        }  
  82.    
  83.        float get_height()  
  84.        {  
  85.               return height;  
  86.        }  
  87.    
  88.        float get_chinese()  
  89.        {  
  90.               return chinese;  
  91.        }  
  92.    
  93.        float get_english()  
  94.        {  
  95.               return english;  
  96.        }  
  97.    
  98.        float get_math()  
  99.        {  
  100.               return math;  
  101.        }  
  102. };  
  103.    
  104. int main(int argc,char**argv)  
  105. {  
  106.        map stu_map;  
  107.    
  108.        Studentstu4(4, "Dudley",1.1f, 170.2f, 90.5f, 89.5f, 93.0);  
  109.        Studentstu3(3, "Chris", 1.1f, 163.4f, 93.5f,90.0f, 83.5f);  
  110.        Studentstu2(2, "Bob", 1.5f, 166.6f, 86.0f,98.5f, 85.0f);  
  111.        Studentstu1(1, "Andrew", 1.5f, 173.2f, 98.5f,100.0f, 100.f);  
  112.    
  113.        stu_map.insert(make_pair(key(stu4.get_eyesight(),stu4.get_height()), stu4));  
  114.        stu_map.insert(make_pair(key(stu3.get_eyesight(),stu3.get_height()), stu3));  
  115.        stu_map.insert(make_pair(key(stu2.get_eyesight(),stu2.get_height()), stu2));  
  116.        stu_map.insert(make_pair(key(stu1.get_eyesight(),stu1.get_height()), stu1));  
  117.    
  118.        map::iterator iter;  
  119.        for(iter = stu_map.begin(); iter != stu_map.end();++iter)  
  120.        {  
  121.              coutfirst.eyesight "\t"first.height  "\t" second.get_id()"\t" second.get_name() 
  122.        }  
  123.    
  124.        return 0;  
  125. }  

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
Optimize the performance of Go language map Optimize the performance of Go language map Mar 23, 2024 pm 12:06 PM

Optimizing the performance of Go language map In Go language, map is a very commonly used data structure, used to store a collection of key-value pairs. However, map performance may suffer when processing large amounts of data. In order to improve the performance of map, we can take some optimization measures to reduce the time complexity of map operations, thereby improving the execution efficiency of the program. 1. Pre-allocate map capacity. When creating a map, we can reduce the number of map expansions and improve program performance by pre-allocating capacity. Generally, we

How to sort WPS scores How to sort WPS scores Mar 20, 2024 am 11:28 AM

In our work, we often use wps software. There are many ways to process data in wps software, and the functions are also very powerful. We often use functions to find averages, summaries, etc. It can be said that as long as The methods that can be used for statistical data have been prepared for everyone in the WPS software library. Below we will introduce the steps of how to sort the scores in WPS. After reading this, you can learn from the experience. 1. First open the table that needs to be ranked. As shown below. 2. Then enter the formula =rank(B2, B2: B5, 0), and be sure to enter 0. As shown below. 3. After entering the formula, press the F4 key on the computer keyboard. This step is to change the relative reference into an absolute reference.

How to implement a custom comparator in C++ STL? How to implement a custom comparator in C++ STL? Jun 05, 2024 am 11:50 AM

Implementing a custom comparator can be accomplished by creating a class that overloads operator(), which accepts two parameters and indicates the result of the comparison. For example, the StringLengthComparator class sorts strings by comparing their lengths: Create a class and overload operator(), returning a Boolean value indicating the comparison result. Using custom comparators for sorting in container algorithms. Custom comparators allow us to sort or compare data based on custom criteria, even if we need to use custom comparison criteria.

Unpatchable Yubico two-factor authentication key vulnerability breaks the security of most Yubikey 5, Security Key, and YubiHSM 2FA devices Unpatchable Yubico two-factor authentication key vulnerability breaks the security of most Yubikey 5, Security Key, and YubiHSM 2FA devices Sep 04, 2024 pm 06:32 PM

An unpatchable Yubico two-factor authentication key vulnerability has broken the security of most Yubikey 5, Security Key, and YubiHSM 2FA devices. The Feitian A22 JavaCard and other devices using Infineon SLB96xx series TPMs are also vulnerable.All

How to sort WPS tables to facilitate data statistics How to sort WPS tables to facilitate data statistics Mar 20, 2024 pm 04:31 PM

WPS is a very complete office software, including text editing, data tables, PPT presentations, PDF formats, flow charts and other functions. Among them, the ones we use most are text, tables, and demonstrations, and they are also the ones we are most familiar with. In our study work, we sometimes use WPS tables to make some data statistics. For example, the school will count the scores of each student. If we have to manually sort the scores of so many students, it will be really a headache. In fact, we don’t have to worry, because our WPS table has a sorting function to solve this problem for us. Next, let’s learn how to sort WPS together. Method steps: Step 1: First we need to open the WPS table that needs to be sorted

How to get the size of a C++ STL container? How to get the size of a C++ STL container? Jun 05, 2024 pm 06:20 PM

You can get the number of elements in a container by using the container's size() member function. For example, the size() function of the vector container returns the number of elements, the size() function of the list container returns the number of elements, the length() function of the string container returns the number of characters, and the capacity() function of the deque container returns the number of allocated memory blocks.

How to sort in excel How to sort in excel Mar 05, 2024 pm 04:12 PM

Sorting methods in excel: 1. Single column sorting; 2. Multiple column sorting; 3. Custom sorting. Detailed introduction: 1. Single-column sorting is the most common sorting method. It sorts according to a selected column; 2. Multi-column sorting refers to sorting data in multiple columns, usually sorting according to a certain column first. On the basis of, sort by another column; 3. Custom sorting, allowing users to define the sort order according to their own needs.

How to deal with hash collisions when using C++ STL? How to deal with hash collisions when using C++ STL? Jun 01, 2024 am 11:06 AM

The methods for handling C++STL hash conflicts are: chain address method: using linked lists to store conflicting elements, which has good applicability. Open addressing method: Find available locations in the bucket to store elements. The sub-methods are: Linear detection: Find the next available location in sequence. Quadratic Detection: Search by skipping positions in quadratic form.

See all articles