对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;
}
}

既然是按照小于号来排序的,那么,如果插入的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的删除:
- earse()函数:删除Map中的条目(一个或多个)
该成员方法的定义如下:
iterator erase(iterator it);// 通过一个条目对象删除
iterator erase(iterator first,iterator last)// 删除一个范围
size_type erase(const Key&key);// 通过关键字删除
-
clear()函数:直接将整个Map删除
相当于erase(Map.begin(),Map.end())
PS:
- 关于Map的删除,就不演示代码了,大家可以自己动手练习练习。
- 还有关于Map的嵌套查询,其实也就是循环遍历Map,再一个个erase,这个可以看这篇博客。
写在最后:
参考资料:
最近接触Map比较频繁,故整理整理知识,以便下次翻阅。
网友评论