map是C++ STL的一种关联容器,它是一种一对一的数据处理方式,
map的基本格式:
map<typename,typename>自定义的名字;比如map<int,string>studentMap;
map的基本操作函数:
C++ Maps是一种关联式容器,包含“关键字/值”对
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的函数
map的插入:
map<int,string>studentMap;
(1)studentMap.insert(pair<int,string>(1,"xiaoming"));
(2)studentMap.insert(map<int,string>::value_type(1,"xiaoming"));
(3)studentMap[1]="xiaoming";
也可以插入自己定义的对象,格式是一样的
map的查找:
map自身查找使用find(),通过该函数返回一个key,如果没找到就返回指向map尾部的迭代器
举例:
#include <map>
#include <string>
#include <iostream>
Using namespace std;
Int main()
{
Map<int, string> mapStudent;
mapStudent.insert(pair<int, string>(1, “student_one”));
mapStudent.insert(pair<int, string>(2, “student_two”));
mapStudent.insert(pair<int, string>(3, “student_three”));
map<int, string>::iterator iter;//定义前向迭代器
iter = mapStudent.find(1);//查找key为1的值
if(iter != mapStudent.end())
{
Cout<<”Find, the value is ”<<iter->second<<endl;
}
Else
{
Cout<<”Do not Find”<<endl;
}
}
map的遍历:
#include <map>
#include <string>
#include <iostream>
Using namespace std;
Int main()
{
Map<int, string> mapStudent;
mapStudent.insert(pair<int, string>(1, “student_one”));
mapStudent.insert(pair<int, string>(2, “student_two”));
mapStudent.insert(pair<int, string>(3, “student_three”));
map<int, string>::iterator iter;//定义前向迭代器
for(iter=mapStudent.begin();iter!=mapStudent.end();iter++)
{
Cout<<iter->first<<” ”<<iter->second<<endl;
}
}