STL | Map(映射)的使用(二)

2019-06-12  本文已影响0人  0与1的邂逅

对Map进行排序:

前面我们已经讲了Map的一些常见用法,同时提到了Map是有序的,自动按照Key进行升序排序(STL中默认是采用小于号来排序的)。下面我们通过前面的一段代码来验证Map的有序性。

#include<iostream>
#include<cstdio>
#include<map>
using namespace std;

typedef map<char,int>m;
m Map;

int main()
{
    char ch;
    for(int i=0;i<5;i++)
    {
        cout<<"input character:";
        cin>>ch;
        //Map.insert(m::value_type(ch,i));
        //Map.insert(pair<char,int>(ch,i));
        Map[ch]=i;
    }
    // 前向迭代器遍历 
    map<char,int>::iterator iter;// 前向迭代器 
    for(iter=Map.begin();iter!=Map.end();iter++)
    {
        cout<<iter->first<<" "<<iter->second<<endl;
    }   
} 
Map的有序性(按Key升序排序)

既然是按照小于号来排序的,那么,如果插入的Key的类型是结构体,因为结构体不支持小于号运算,所以当涉及到排序操作时就会出现问题。

我们要怎么来解决呢?主要有下面两种方法。


#include<iostream>
#include<cstdio>
#include<vector>
#include<map>
using namespace std;

typedef struct Student
{
    int age;
    int score;
    // 重载小于号 
    bool operator <(Student const& temp)const
    {
        if(age<temp.age)return true;
        else if(age==temp.age)
        {
            if(score<temp.score)return true;
            else return false;
        }
        else if(age>temp.age)return false;
    } 
}Student;
vector<Student>students;
typedef map<Student,int> m;
m Map;

int main()
{
    int n;
    cout<<"input the total numberof students:";
    cin>>n;
    Student temp;
    for(int i=0;i<n;i++)
    {
        cout<<"input the age and score of student:";
        cin>>temp.age>>temp.score;
        Map[temp]=i;
        students.push_back(temp);
    } 
    m::iterator iter;
    for(iter=Map.begin();iter!=Map.end();iter++)
    {
        cout<<iter->first.age<<" "<<iter->first.score<<endl;
    }
} 
运行结果
#include<iostream>
#include<cstdio>
#include<vector>
#include<map>
using namespace std;

typedef struct Student
{
    int age;
    int score;
}Student;
vector<Student>students;
// 仿函数 
class sort
{
    public:
        bool operator()(Student const &A,Student const &B)
        {
            if(A.age<B.age)return true;
            else if(A.age==B.age)
            {
                if(A.score<B.score)return true;
                else return false;
            }
            else if(A.age>B.age)return false;
        }   
};
typedef map<Student,int,sort> m;
m Map;

int main()
{
    int n;
    cout<<"input the total numberof students:";
    cin>>n;
    Student temp;
    for(int i=0;i<n;i++)
    {
        cout<<"input the age and score of student:";
        cin>>temp.age>>temp.score;
        Map[temp]=i;
        students.push_back(temp);
    } 
    m::iterator iter;
    for(iter=Map.begin();iter!=Map.end();iter++)
    {
        cout<<iter->first.age<<" "<<iter->first.score<<endl;
    }
} 

Map的删除:

该成员方法的定义如下:

iterator erase(iterator it);// 通过一个条目对象删除

iterator erase(iterator first,iterator last)// 删除一个范围

size_type erase(const Key&key);// 通过关键字删除

PS:

写在最后:

参考资料:

最近接触Map比较频繁,故整理整理知识,以便下次翻阅。

上一篇 下一篇

猜你喜欢

热点阅读