映射是C++ STL(标准模板库)的一部分。映射是存储排序的键值对的关联集合,其中每个键都是唯一的,可以插入或删除但不能更改。与键关联的值可以更改。
例如:一张员工图,其中员工ID是键,姓名是值,可以表示为:
键 | 值 |
---|---|
101 | 张三丰 |
102 | 朱重八 |
103 | 李自成 |
104 | 王莽 |
template < class Key, //map::key_type class T, //map::mapped_type class Compare = less<Key>, //map::key_compare class Alloc = allocator<pair<const Key,T> > //map::allocator_type > class map;
class - 要存储在映射中的键数据类型。
type - 要存储在映射中的值的数据类型。
compare - 一个比较类,该类接受两个bool类型相同的参数并返回一个值。此参数是可选的,二进制谓词less是默认值。
alloc - 分配器对象的类型。此参数是可选的,默认值为分配器
使用以下语句可以轻松创建Map映射:
typedef pairvalue_type;
上面的表单将用于创建具有 Key type 类型的键和 value type类型的值的Map。重要的一点是,Map的键和对应的值始终是成对插入时,您不能在Map中仅插入键或仅插入值。
#include <string.h> #include <iostream> #include <map> #include <utility> using namespace std; int main() { map<int, string> Employees; //1) Assignment using array index notation Employees[101] = "Nikita"; Employees[105] = "Learnfk"; Employees[103] = "Dolly"; Employees[104] = "Deep"; Employees[102] = "Aman"; cout << "Employees[104]=" << Employees[104] << endl << endl; cout << "Map size: " << Employees.size() << endl; cout << endl << "Natural Order:" << endl; for( map<int,string>::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii) { cout << (*ii).first << ": " << (*ii).second << endl; } cout << endl << "Reverse Order:" << endl; for( map<int,string>::reverse_iterator ii=Employees.rbegin(); ii!=Employees.rend(); ++ii) { cout << (*ii).first << ": " << (*ii).second << endl; } }
输出:
Employees[104]=Deep Map size: 5 Natural Order: 101: Nikita 102: Aman 103: Dolly 104: Deep 105: Learnfk Reverse Order: 105: Learnfk 104: Deep 103: Dolly 102: Aman 101: Nikita
以下是map的所有成员函数的列表:
函数 | 说明 |
---|---|
constructors | 构建映射 |
destructors | 映射析构函数 |
operator = | 将映射的元素复制到另一张映射。 |
函数 | 说明 |
---|---|
begin | 返回指向映射中第一个元素的迭代器。 |
cbegin | 返回指向映射中第一个元素的const迭代器。 |
end | 返回指向末尾的迭代器。 |
cend | 返回一个指向末尾的常量迭代器。 |
rbegin | 返回指向结尾的反向迭代器。 |
rend | 返回指向起点的反向迭代器。 |
crbegin | 返回一个常量ant反向迭代器指向结束。 |
credit | 返回指向起点的常量反向迭代器。 |
函数 | 说明 |
---|---|
empty | 如果映射为空,则返回true。 |
size | 返回映射中的元素数量。 |
max_size | 返回映射的最大尺寸。 |
函数 | 说明 |
---|---|
operator [] | 使用给定的键检索元素。 |
| 使用给定的键检索元素。 |
函数 | 说明 |
---|---|
insert | 在映射中插入元素。 |
erase | 从映射上擦除元素。 |
swap | 交换映射内容。 |
clear | 删除映射的所有元素。 |
emplace | 构造新元素并将其插入映射。 |
emplace_hint | 通过提示构造新元素并将其插入映射。 |
函数 | 说明 |
---|---|
key_comp | 返回键比较对象的副本。 |
value_comp | 返回值比较对象的副本。 |
函数 | 说明 |
---|---|
find | 搜索具有给定键的元素。 |
count | 获取与给定键匹配的元素数。 |
lower_bound | 将迭代器返回到下限。 |
upper_bound | 将迭代器返回上限。 |
equal_range | 返回与给定键匹配的元素的参数。 |
get_allocator | 返回用于构造映射的分配器对象。 |
Functions | Description |
---|---|
operator== | 检查两个映射是否相等。 |
operator!= | 检查两个映射是否相等。 |
operator | 检查第一张映射是否小于其他映射。 |
operator | 检查第一张映射是否小于或等于其他映射。 |
operator> | 检查第一张映射是否大于其他映射。 |
operator>= | 检查第一张映射是否大于其他映射。 |
swap() | 交换两个映射的元素。 |
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)