C++ STL之映射:map

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xnh_565175944/article/details/83210511

一、简介

       map是STL中的一个关联容器,用来存储若干元素,这些元素都是由关键值key映射值value配对组成。

二、map

       在map内部,元素按照key值进行排序,排序方式是根据某种明确、严格的若排序进行的。

       map的所有元素都是pair,pair的第一个元素是key,第二个元素是value

       map中的映射值可以通过运算符[]中关联key直接访问,用法类似于数组。

       因为map通常是由二叉搜索树实现,所以访问的时间为O(n)

注意: map中的key值是唯一的

map常用函数

功能

clear()

清除map中所有函数

erase()

删除map中指定位置的元素

insert()

在map指定位置添加pair类型元素

find()

获取指定key值map的迭代器

begin()

map的正向迭代器的起始位置

end()

map的正向迭代器的终点位置

 

 

简单演示:

#include <iostream>
#include <map>
using namespace std;

int main()
{
	map<string,string> student;
	//map<key,value> <map-name>
	 
	string name,no;
	while( cin >> name >> no  )	
	{
		student[name] = no;
	}
	map<string,string>::iterator it;
	
	for(it = student.begin(); it != student.end(); ++it)
	{
		cout << "姓名:" << it->first << " 学号:" << it->second << "\n";
	}
	if( student.count("liang") ) cout << "liang的学号是:" << student["liang"] << endl;
	cout << "clear前长度为:" << student.size() << endl;
	student.clear(); 
	cout << "clear后长度为:" << student.size() << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/xnh_565175944/article/details/83210511