map的定义
1 | map<typename1,typename2>mp; |
这里的类型如果要用字符串的话只能用string,不能用char[]
元素插入
用insert函数插入pair数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19///数据的插入--第一种:用insert函数插入pair数据
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;
///反向
// map<int, string>::reverse_iterator iter;
// for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++)
// cout<<iter->first<<" "<<iter->second<<endl;
}用nsert函数插入value_type数据
1
2
3
4
5
6
7
8
9
10
11
12
13
using namespace std;
int main() {
map<int, string> mapStudent;
mapStudent.insert(map<int, string>::value_type (1, "student_one"));
mapStudent.insert(map<int, string>::value_type (2, "student_two"));
mapStudent.insert(map<int, string>::value_type (3, "student_three"));
map<int, string>::iterator iter;
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout<<iter->first<<' '<<iter->second<<endl;
}直接用数组方式插入数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using namespace std;
int main() {
map<int, string> mapStudent;
mapStudent[1] = "student_one";
mapStudent[2] = "student_two";
mapStudent[3] = "student_three";
map<int, string>::iterator iter;
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout<<iter->first<<' '<<iter->second<<endl;
// int nSize = mapStudent.size();
///此处应注意,应该是 for(int nindex = 1; nindex <= nSize; nindex++)
///而不是 for(int nindex = 0; nindex < nSize; nindex++)
// for(int nindex = 1; nindex <= nSize; nindex++)
// cout<<mapStudent[nindex]<<endl;
}
元素查找
- 用 count() 函数来判定 key 是否出现,其缺点是无法定位数据出现位置,由于map的特性,一对一的映射关系,就决定了count函数的返回值只有两个,要么是0,要么是1,出现的情况,当然是返回1了
- 用 find 函数来定位 key 出现位置,它返回的一个 迭代器,当数据出现时,它返回数据所在位置的迭代器,如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器。
操作函数
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的函数