C++的map介绍以及插入操作

一 点睛

Map是STL的一个关联容器,它提供一对一(其中第一个称为关键字,每个关键字只能在map中出现一次,第二个称为该关键字的值)的数据处理能力。map内部自建一颗红黑树(一 种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的。

C++的map介绍以及插入操作_第1张图片

1 map简介

map是一类关联式容器。它的特点是增加和删除节点对迭代器的影响很小,除了那个操作节点,对其他的节点都没有什么影响。

对于迭代器来说,可以修改值,而不能修改key。

2 map的功能

自动建立Key - value的对应。key 和 value可以是任意你需要的类型。

根据key值快速查找记录,查找的复杂度基本是Log(N),如果有1000个记录,最多查找10次,1,000,000个记录,最多查找20次。

快速插入Key -Value 记录。

快速删除记录

根据Key修改value记录。

遍历所有记录。

3 使用map

使用map得包含map类所在的头文件

#include

map对象是模板类

template,
         class Allocator = allocator>>
class map;

其中:

  • Key:关键字类型,每个元素都被关键字Key独一无二地标识。
  • T:元素类型。每一个元素都可以存放一些数据。
  • Compare:比较类。
  • allocator:它表示存储管理设备。

4 map的插入有3种方式:用insert函数插入pair数据,用insert函数插入value_type数据和用数组方式插入数据。

二 用insert函数插入pair数据

1 代码

#include 
#include 
#include 
using namespace std;
int main()
{
    map mapStudent;
    mapStudent.insert(pair(1, "student_one"));
    mapStudent.insert(pair(2, "student_two"));
    mapStudent.insert(pair(3, "student_three"));
    map::iterator iter;
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++){
       cout<first<<" "<second<

2 运行

[root@localhost charpter03]# g++ 0318.cpp -o 0318
[root@localhost charpter03]# ./0318
1 student_one
2 student_two
3 student_three

3 说明

pair的定义

template 
struct pair{
  typedef T1 first_type;
  typedef T2 second_type;
  T1 first;//注意,它是public
  T2 second;//注意,它是public
  pair() : first(T1()),second(T2()) {}
  pair(const T1&a,const T2&b) :first(a),second(b) {}

};

该例定义了一个key为int类型,value为string类型的map,用insert插入pair,在insert的参数中将(1,"student_one")转换为pair数据再进行插入。

三 用insert函数插入value_type数据

1 代码

#include 
#include 
#include 
using namespace std;
int main()
{
    map mapStudent;
    mapStudent.insert(map::value_type (1,"student_one"));
    mapStudent.insert(map::value_type (2,"student_two"));
    mapStudent.insert(map::value_type (3,"student_three"));
    map::iterator  iter;
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++){
       cout<first<<" "<second<

2 运行

[root@localhost charpter03]# g++ 0319.cpp -o 0319
[root@localhost charpter03]# ./0319
1 student_one
2 student_two
3 student_three

3 说明

声明了一个key为int类型,value为string类型的map,用insert函数插入value_type数据,插入前,需要将(1,"student_one")转换为map::value_type数据再插入。

四 map中用数组方式插入数据

1 代码

#include 
#include 
#include 
using namespace std;
int main(){
    map mapStudent;
     mapStudent[1] =  "student_one";
     mapStudent[2] =  "student_two";
     mapStudent[3] =  "student_three";
    map::iterator  iter;
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++){
          cout<first<<"  "<second<

2 运行

[root@localhost charpter03]# g++ 0320.cpp -o 0320
[root@localhost charpter03]# ./0320
1  student_one
2  student_two
3  student_three

3 说明

展示了用数组方式在map中插入数据,和数组访问一样,有下标、直接赋值。

你可能感兴趣的:(C++)