C++STL map介绍与使用方法

map(映射)

map是STL的一个关联容器,它提供一对一的数据处理能力(其中第一个可以成为关键字,且每个关键字只能在map出现一次,第二个可以称为该关键之的值),将关键字与该关键字的值组合在一起进行存储。由于具有一对一的特性,它能够完成我们处理一对一的数据时,在编程上提供快速通道。前面容器对比提到,map内部数据结构是红黑树(一种非严格意义上的平衡二叉树),这棵树具有对数据自动排序的功能,所以在map内所有的数据数据都是有序的。
map最为明显的用处便是统计次数,比如统计单词的个数。直接利用字符串作为关键字会非常方便。


头文件:#include
map基本特性
  • 关联容器内元素是由关键字进行引用的,而不是其绝对位置
  • 容器内的元素从始至终都保持着某种严格的顺序,每一个被插入的元素都被放到了正确的位置
  • 每一个元素将一个关键字与一个值进行关联,关键字能够识别其具体内容
  • 关键字必须唯一,在一个容器内不会出现两个重复的关键字
  • 动态分配内存

map与其它容器不一样,由于每个元素是键值对,每个元素里面关键字与该关键字的值类型可以不一样,因此在定义map时必须制定key/value分别的类型,所以尖括号内有

构造函数

bool fncomp (char lhs, char rhs) {return lhs<rhs;}

struct classcomp {
    bool operator() (const char& lhs, const char& rhs) const
    {return lhs<rhs;}
};

map<char, int> first;
first['a']=10;
first['b']=30;
first['c']=50;
first['d']=70;

map<char, int> second(first.begi(), first.end());
map<char, int> third(second);
map<char, int, classcomp> fourth;   // 

bool(*fn_pt)(char,char) = fncomp;
std::map<char,int,bool(*)(char,char)> fifth (fn_pt); // function pointer as Compare


迭代器
  • 与其它容器一样,map一样有迭代器,但又有些不同,比如vector, string这样的容器,迭代器直接指向一个元素,通过迭代器直接得到某个元素的值。但map里面每个元素是一个键值对,数据类型为std::pair
map<char, int> first;
first['a']=10;
first['b']=30;
first['c']=50;
first['d']=70;

map<char, int>::iterator it;
map<char, int>::reverse_iterator rit;

it = first.begin();
it = first.end();
rbegin = rit.begin();
rend = rit.end();

//利用for each访问容器
for each(std::pair<char, int> m in first)
{

    cout << m.first << " " << m.second << endl;
}

//利用iterator访问容器元素
for (it = first.begin(); it != first.end(); it++)
{
    //利用iterator访问每一个元素的内部成员(迭代器可以想象成指针)
    cout << it->first << " " << it->second << endl;
    //cout << (*it).first << " " << (*it).second << endl;
}
容器大小
map<char, int> first;
first['a']=10;
first['b']=30;
first['c']=50;
first['d']=70;

cout << first.max_size() << endl;   //map的最大空间大小
bool emp = first.empty();   //测试是否为空
if (!first.empty())
{
    cout << first.size() << endl;   //map的大小(元素个数)

}

元素访问
  • 直接利用[]符号进行访问map元素,[]内的值为要查找的关键字,如map[‘a’], 假如map内已有某一元素关键字为’a’,则返回该关键字相关联的值,若没有找打该关键字,则会将该关键字插入到map内,因此可以直接利用[]的方式向map内插入元素
map<string, string> myMap;

myMap["lily"] = "what's up?";
myMap["tom"] = "ok, you win";
myMap["jack"] = "hi, cena.";

cout << myMap["tom"] << endl;


//在C++11里面还提供了at函数,at函数与[]的区别是不能添加元素,如果没有查找到关键之,则会抛出out_of_range异常
cout << myMap.at("lily") << endl;
myMap.at("jack") = "oh my god";  //利用at函数修改map
修改map
//插入元素
//插入操作首先会检查要插入的键值对的关键字是否已经在map里面,如果已经存在,则插入失败。返回这个已经存在的元素的迭代器
map<char, int> first;

mymap.insert ( std::pair<char,int>('z',200) );

std::pair<std::map<char,int>::iterator,bool> ret;
ret = mymap.insert ( std::pair<char,int>('z',500) ); //返回值为一个pair,pair的key为insert函数返回的迭代器,value为bool变量,表示是否成功插入。
if (ret.second==false) {
std::cout << "element 'z' already existed";
std::cout << " with a value of " << ret.first->second << '\n';
}

map<char, int>::iterator it;
it = first.insert(pair<char, int>('e', 200));


//删除元素
//删除元素三个版本
iterator  erase (const_iterator position);
size_type erase (const key_type& k);
iterator  erase (const_iterator first, const_iterator last);

std::map<char,int> mymap;
std::map<char,int>::iterator it;

// insert some values:
mymap['a']=10;
mymap['b']=20;
mymap['c']=30;
mymap['d']=40;

mymap.erase('c');  //通过key删除
mymap.erase(mymap.begin());
mymap.erase(mymap.begin(), mymap.end());  //删除所有


//交换 清空
map<char, int> second;
mymap.swap(second);
mymap.clear();  //清空所有元素
其它操作
查找
函数模板
iterator find (const key_type& k);
const_iterator find (const key_type& k) const;

//从函数模板可以看出查找就只能通过关键字查找

返回值:如果查找到某元素,则返回该元素迭代器,否则返回map::end

std::map<char,int> mymap;
std::map<char,int>::iterator it;

mymap['a']=50;
mymap['b']=100;
mymap['c']=150;
mymap['d']=200;


//注意在使用过程中,一定要先判断是否查找到
it = first.find('z');

if (it != first.end())
{
    cout << it->first << " " << it->second << "\n";
}
cout << "a => " << mymap.find('a')->second << '\n';
cout << "c => " << mymap.find('c')->second << '\n';
cout << "d => " << mymap.find('d')->second << '\n';

map应用
  • 由于map内不是用红黑树实现的,因此每次插入一个元素都会将其放到树的正确位置。在搜寻位置过程中,必然会与将官架子其它元素的关键字进行比较。对于关键字是内部类型(如int, char),可以直接进行比较,但如果关键字使用的是用户自定义的类或者结构体,则必须要自己重载操作符<。下面是网上摘录的一段代码, 很清晰的解释了如何使用自定义类作为关键字。
#include<string>
#include<iostream>
#include<map>
using namespace std;
struct person
{
    string name;
    int age;
    person(string name, int age)
    {
        this->name =  name;
        this->age = age;
    }
    bool operator < (const person& p) const
    {
        return this->age < p.age;
    }
};
map<person,int> m;
int main()
{
    person p1("Tom1",20);
    person p2("Tom2",22);
    person p3("Tom3",22);
    person p4("Tom4",23);
    person p5("Tom5",24);
    m.insert(make_pair(p3, 100));
    m.insert(make_pair(p4, 100));
    m.insert(make_pair(p5, 100));
    m.insert(make_pair(p1, 100));
    m.insert(make_pair(p2, 100));   
    for(map<person, int>::iterator iter = m.begin(); iter != m.end(); iter++)
    {
        cout<<iter->first.name<<"\t"<<iter->first.age<<endl;
    }   
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值