map是用来存放<key, value>
键值对的数据结构容器,可以很方便快速的根据key查到相应的value。假如存储学生和其成绩(假定不存在重名,当然可以对重名加以区分),我们用map来进行存储就是个不错的选择。 我们这样定义,map<string, int>
,其中学生姓名用string类型,作为Key;该学生的成绩用int类型,作为value。这样一来,我们可以根据学生姓名快速的查找到他的成绩。
但是,我们除了希望能够查询某个学生的成绩,或许还想看看整体的情况。我们想把所有同学和他相应的成绩都输出来,并且按照我们想要的顺序进行输出:比如按照学生姓名的顺序进行输出,或者按照学生成绩的高低进行输出。换句话说,我们希望能够对map进行按Key排序或按Value排序,然后按序输出其键值对的内容。
下面来看排序函数:
#include <map>
#include <string>
#include <iostream>
using namespace std;
struct CmpByKeyLength {
bool operator()(const int& k1, const int& k2) {
return k1 > k2;
}
};
class testmap {
public:
testmap() { m_x = 0; m_str = ""; }
testmap(int _x, string _str) {
m_x = _x;
m_str = _str;
}
void init(int a,string b) {
m_x = a;
m_str = b;
}
int m_x;
string m_str;
};
class cmpmap {
public:
cmpmap(void) {};
bool operator ()(const testmap &_a, const testmap &_b) {
return _a.m_x > _b.m_x;
}
};
typedef map<testmap,int,cmpmap> mappag;
typedef map<int,string, CmpByKeyLength> mappag2;
int main()
{
mappag2 mapstruct;
mappag mapStudent;
testmap test(1, "apple");
mapStudent.insert(pair<testmap, int>(test, 10));
test.init(0, "apo");
mapStudent.insert(pair<testmap, int>(test, 10));
test.init(10, "find");
mapStudent.insert(pair<testmap, int>(test, 10));
test.init(20, "love");
mapStudent.insert(pair<testmap, int>(test, 10));
mapstruct.insert(pair<int, string>(10, "apple"));
mapstruct.insert(pair<int, string>(20, "wing"));
mapstruct.insert(pair<int, string>(30, "like"));
mapstruct.insert(pair<int, string>(40, "bear"));
cout << "按照类定义从大到小排序" << endl;
map<testmap,int>::iterator iter;
for (iter = mapStudent.begin(); iter != mapStudent.end(); ++iter)
cout << iter->first.m_x << ' ' << iter->first.m_str << endl;
cout << "按照结构体定义比较方法排序" << endl;
map<int,string>::iterator it;
for (it = mapstruct.begin(); it != mapstruct.end(); ++it)
cout << it->first << " " << it->second << endl;
return 0;
}
该程序使用了两种方法进行降序排列,一种使用结构体进行排序,另一种使用类定义进行排序。其中,结构体排序为CmpByKeyLength,源码:
struct CmpByKeyLength {
bool operator()(const int& k1, const int& k2) {
return k1 > k2;
}
};
类定义用的的三种类型的关联,其中前面两种类型是在内中定义的,源码:
class testmap {
public:
testmap() { m_x = 0; m_str = ""; }
testmap(int _x, string _str) {
m_x = _x;
m_str = _str;
}
void init(int a,string b) {
m_x = a;
m_str = b;
}
int m_x;
string m_str;
};
class cmpmap {
public:
cmpmap(void) {};
bool operator ()(const testmap &_a, const testmap &_b) {
return _a.m_x > _b.m_x;
}
};
欢迎大家前来交流~