【转载】C++中map的用法
map的特性是,所有元素都会根据元素的减值自动被排序。map的所有元素都是pair,同时拥有实值(value)和键值(key)。pair的第一个元素会被视为键值,第二个元素会被视为实值。map不允许两个元素拥有相同的键值。
下面看一下
template
struct pair{
typedef T1 first_type;
typedef T2 second_type;
T1 first;//注意,它是public
T2 second;//注意,它是public
pair() : first(T1()),second(T2()) {}
pair(const T1&a,const T2&b) :first(a),second(b) {}
};
当客户端对map进行元素新增操作(insert)和删除(erase)时,操作之前的所有迭代器,在操作完成之后依然有效。被删除的迭代器除外。
标准的STL map是以红黑树为底层机制完成的,每一个节点的内容是一个pair。
一、map的基本构造函数
map
map
map
map< char ,string>charMap;
map
map
二、map添加数据
map
1.pair
等价于maplive.insert(pair
2. maplive.insert(map
3. maplive[1]="a";//map中最简单最常用的插入添加!
三、map的基本操作函数:
begin() 返回指向map头部的迭代器
clear() 删除所有元素
count() 返回指定元素出现的次数
empty() 如果map为空则返回true
end() 返回指向map末尾的迭代器
equal_range() 返回特殊条目的迭代器对
erase() 删除一个元素
find() 查找一个元素
get_allocator() 返回map的配置器
insert() 插入元素
key_comp() 返回比较元素key的函数
lower_bound() 返回键值>=给定元素的第一个位置
max_size() 返回可以容纳的最大元素个数
rbegin() 返回一个指向map尾部的逆向迭代器
rend() 返回一个指向map头部的逆向迭代器
size() 返回map中元素的个数
swap() 交换两个map
upper_bound() 返回键值>给定元素的第一个位置
value_comp() 返回比较元素value的函数
来自 <>
- #include
- #include "string.h"
- #include "stdio.h"
- #include
- using namespace std;
- int main(){
- map
int> strMap; //以string为键值,以int为实值 - strMap[string("jjhou")] = 1;
- strMap[string("jerry")] = 2;
- strMap[string("jason")] = 3;
- strMap[string("jimmy")] = 4;
- pair
int> value(string("david"),5); - strMap.insert(value);//插入新元素
- map
int>::iterator strmap_iter = strMap.begin(); - for(;strmap_iter !=strMap.end();strmap_iter++)
- {
- cout<
first<<' '< second< - }
- cout<
- int number = strMap[string("jjhou")];
- cout<
- cout<
- //查找元素
- map
int>::iterator iter1; - //面对关联式容器,应该使用其所提供的find函数来搜索元素,会比使用STL算法find()更有效率。因为STL算法find()只是循环搜索。
- iter1 = strMap.find(string("mchen"));
- if(iter1 == strMap.end())
- cout<<"mchen no fount"<
- cout<
- iter1 = strMap.find(string("jerry"));
- if(iter1 != strMap.end())
- cout<<"jerry fount"<
- cout<
- //修改实值,键值不可修改
- iter1->second = 9; //可以通过map迭代器修改"value"(not key)
- int number1 = strMap[string("jerry")];
- cout<
- //删除元素
- map
int>::iterator strmap_iter1 = strMap.begin(); - for(;strmap_iter1 !=strMap.end();strmap_iter1++)
- {
- cout<
first<<' '< second< - }
- cout<
- strMap.erase(iter1);//删除一个条目
- strMap.erase(string("jason"));//根据键值删除
- map
int>::iterator strmap_iter2 = strMap.begin(); - for(;strmap_iter2 !=strMap.end();strmap_iter2++)
- {
- cout<
first<<' '< second< - }
- }
-
//逆序扫描map
for(map
::reverse_iterator it=poly.rbegin();it!=poly.rend();it++) 来自