2020-10-28

映射

template <class Key, class T, class Compare = less<Key>, class Alloc = allocator<pair<const Key, T> > > class map;

< map >

介绍

映射是一种关联容器,元素按按顺序排列,有“键”和“值”组成。
在映射中,“键”通常用来排序而且唯一标识了一个元素,而“值”为一个“键”所关联的内容。“键”和“值”的类型可能不同,而且会被组合在成员类型value_type中,它是pair类型

typedef pair<const Key, T> value_type;

在内容,元素会依据它们的“键”根据内部比较对象的“弱排序准则”来排序。
就像set和unordered_set,map在读取元素上要比unordered_map慢,但是允许子集按照顺序来直接迭代。
映射中的值可以直接通过关联的“键”和中括号[]来读取。
maps常以二叉搜索树的形式实现。

容器属性

  • 关联性
    容器中的元素通过“键”来引用,而不是它们的绝对位置。
  • 有序性
    容器中的元素一直遵循一个严格的顺序,新插入的元素会找到它的位置。
  • 映射性
    每个元素是一个“键”“值”对,“键”用来唯一标识元素,“值”是与之关联的内容。
  • 唯一性
    一个键只对应一个元素。
  • 分配器感知
    使用分配器来动态管理所需内存。

模板参数

  • Key
    “键”的类型,别名map::key_type
  • T
    “值”的类型,别名map::value_type
  • Compare
    二元谓词,用来比较“键”的大小,别名map::key_compare
  • Alloc
    分配器的类型,别名map::allocator_type

成员函数

构造函数
/* 默认 */
explicit map(const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type());
explicit map(const allocator_type& alloc);
/* 范围 */
template <class InputIterator>
map(InputIterator first, InputIterator last, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type());
/* 拷贝构造 */
map(const map& x);
map(const map& x, const allocator_type& alloc);
/* 移动构造 */
map(map&& x);
map(map&& x, const allocator_type& alloc);
/* 初始化列表 */
map(initializer_list<value_type> il, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type());

// 举例
/ constructing maps
#include <iostream>
#include <map>

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

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

int main ()
{
  std::map<char,int> first;

  first['a']=10;
  first['b']=30;
  first['c']=50;
  first['d']=70;

  std::map<char,int> second (first.begin(),first.end());

  std::map<char,int> third (second);

  std::map<char,int,classcomp> fourth;                 // class as Compare

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

  return 0;
}
迭代器
begin() end() rbegin() rend() cbegin() cend() crbegin() crend()
容量
size()
empty()
max_size()
读取元素
operator[]
at()
元素操作
insert()
erase()
swap()
clear()
emplace()
emplace_hint()
find()
count()
lower_bound()
upper_bound()
equal_range()
其它
key_compare()
value_compare()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值