(个人向)map 复习

· · 个人记录

一、map映射

  1. map是STL的一个关联式容器,它提供一对一映射的数据处理能力
  2. map需要关键字和储存对象两个参数,来构造关键字和对象的一一映射
  3. map可以将基本类型、结构体或者STL容器映射到任意基本类型或容器中
  4. map底层用红黑树(一种平衡二叉树)来实现,这棵树会对数据自动排序
  5. map内部所有的数据是根据关键字由小到大排序的
  6. map能够保证关键字的唯一性
  7. 关键字不能被修改,储存对象的值可以被修改
  8. map提供迭代器,所有对于map的操作的时间复杂度都是log(n)级别的
  9. map提供两个公有成员变量first和second
  10. first描述关键字,second描述存储对象

map的基本成员函数:

#include <map>//map头文件

map<string,int>a    //前一个string是关键字,有一个int是对象

a.begin()   //返回映射a中关键字最小的元素的指针

a.end()     //返回映射a的结束标记指针

a.empty()   //返回1,表示映射为空

a.size()    //返回映射中的元素个数

a.clear()   //把map清空

a["one"]=1; //访问关键字为"one"的元素。如果"one"在map中存在,则直接把存储的值修改为1,否则则会在map中加入元素("one",1),并且map的size()会增加1

a.insert()  //向映射a中加入一个元素

a.erase("one")  //把映射中的元素"one"删除

a.erase(it) //把迭代器指向的元素删除

a.erase(itbegin,itend)  //把迭代器指针区间中的元素删除

a.clear()   //把map清空

a.cout("one")   //查找关键字为"one"的元素是否存在,返回1或0

a.find("one")   //查找并返回指向map中的关键字为"one"的指针

a.lower_bound(i)    //返回大于或等于关键字i的最小元素的指针

a.upper_bound(i)    //返回大于关键字i的最小元素的指针

插入元素的两种方式

map<string,int>a;
  1. 用insert插入pair对象

    a.insert(pari<string,int>("one",1));

  2. 用数组的方式插入值,数组下标为关键字,等号右边为对象

    a["two"]=2;

map访问元素的两种方法:

  1. 用iterator方法访问

    it=a.find("two"); cout<<it->first<<" '<<it->second<<endl;

  2. 用数组方式访问,数组下标为关键字,值为存储对象

    cout<<a["one"]<<' '<<a["two"]<<endl;

map映射——使用[ ]访问map的注意事项

#include <bits/stdc++.h>
using namespace std;
map<int,int>a;
map<int,int>::iterator it;
int main()
{
    cout<<a.size()<<endl;
    for(int i=1;i<=10;i++)
        if(a[i])
            printf("YES\n");
    cout<<a.size()<<endl;
    return 0;
}
/*
output:
0
10
*/

map映射——插入数据方法

#include <bits/stdc++.h>
using namespace std;
pair<string,int>p;
map<string,int>mp;
map<string,int>::iterator it;
int main()
{
    mp.insert(map<string,int>::value_type("one",1));
    mp.insert(pair<string,int>("two",2));
    mp.insert(make_pair("three",3));
    p.first="four";
    p.second=4;
    mp.insert(p);
    mp["five"]=5;
    for(it=mp.begin();it!=mp.end();it++)
        cout<<it->first<<' '<<it->second<<endl;
    return 0;
}
/*
output
five 5
fout 4
one 1
three 3
two 2
*/