浅谈c++中的stl中的map用法详解

2020-01-06 15:47:29王冬梅

以上程序是无法编译通过的,只要重载小于号,就OK了,如下:


Typedef struct tagStudentInfo

{

    Int   nID;

    String  strName;

    Bool operator < (tagStudentInfo const& _A) const

    {

       //这个函数指定排序策略,按nID排序,如果nID相等的话,按strName排序

       If(nID < _A.nID) return true;

       If(nID == _A.nID) return strName.compare(_A.strName) < 0;

       Return false;

    }

}StudentInfo, *PStudentInfo; //学生信息

第二种:仿函数的应用,这个时候结构体中没有直接的小于号重载,程序说明


#include <map>

#include <string>

Using namespace std;

Typedef struct tagStudentInfo

{

    Int   nID;

    String  strName;

}StudentInfo, *PStudentInfo; //学生信息

 

Classs sort

{

    Public:

    Bool operator() (StudentInfo const &_A, StudentInfo const &_B) const

    {

       If(_A.nID < _B.nID) return true;

       If(_A.nID == _B.nID) return _A.strName.compare(_B.strName) < 0;

       Return false;

    }

};

 

Int main()

{

    //用学生信息映射分数

    Map<StudentInfo, int, sort>mapStudent;

    StudentInfo studentInfo;

    studentInfo.nID = 1;

    studentInfo.strName = “student_one”;

    mapStudent.insert(pair<StudentInfo, int>(studentInfo, 90));

    studentInfo.nID = 2;

    studentInfo.strName = “student_two”;

mapStudent.insert(pair<StudentInfo, int>(studentInfo, 80));

}

10. 另外

由于STL是一个统一的整体,map的很多用法都和STL中其它的东西结合在一起,比如在排序上,这里默认用的是小于号,即less<>,如果要从大到小排序呢,这里涉及到的东西很多,在此无法一一加以说明。

还要说明的是,map中由于它内部有序,由红黑树保证,因此很多函数执行的时间复杂度都是log2N的,如果用map函数可以实现的功能,而STL  Algorithm也可以完成该功能,建议用map自带函数,效率高一些。

下面说下,map在空间上的特性,否则,估计你用起来会有时候表现的比较郁闷,由于map的每个数据对应红黑树上的一个节点,这个节点在不保存你的数据时,是占用16个字节的,一个父节点指针,左右孩子指针,还有一个枚举值(标示红黑的,相当于平衡二叉树中的平衡因子),我想大家应该知道,这些地方很费内存了吧,不说了……

以上就是小编为大家带来的浅谈c++中的stl中的map用法详解全部内容了,希望大家多多支持ASPKU~


注:相关教程知识阅读请移步到C++教程频道。