写这个博客专栏就是为了以后备用。
简介
Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道。
使用说明
头文件
#include <map>
常用函数
begin() // 返回指向map头部的迭代器
clear() // 删除所有元素
count() // 返回指定元素出现的次数
empty() // 如果map为空则返回true
end() // 返回指向map末尾的迭代器
erase() // 删除一个元素
find() // 查找一个元素
insert() // 插入元素
max_size() // 返回可以容纳的最大元素个数
size() // 返回map中元素的个数
swap() // 交换两个map
使用示例
#include<stdio.h>
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<char, int> a;//定义map函数
// 插入元素
if (!a.count('c')) // 如果没有索引'c'就插入
a.insert(map<char, int>::value_type('c', 1));
if (!a.count('d')) // 如果没有索引'd'就插入
a.insert(map<char, int>::value_type('d', 2));
map<char, int>::iterator b = a.find('c');//查找元素
cout << a['c'] << endl; // 获得索引‘c’的value
cout << a.max_size() << endl; // 返回可以容纳的最大元素个数
cout << a.size() << endl; // 返回map中元素的个数
cout << a.count('c') << endl; // 返回指定'c'元素出现的次数
cout << "d::" << a['d'] << endl;
a['d'] = 3; // 更改值
cout << "d::" << a['d'] << endl;
if (!a.empty())
cout << "a不为空" << endl;
a.clear();//删除所有元素
if (a.empty())
cout << "a为空" << endl;
return 0;
}
简评
C++的map和Java的map有很多相同的地方,可以结合参考参考。