STL学习2:map

map

map本质是一类关联式容器,属于模板类关联的本质在于元素的值与某个特定的键相关联,而并非通过元素在数组中的位置类获取。它的特点是增加和删除节点对迭代器的影响很小,除了操作节点,对其他的节点都没有什么影响。对于迭代器来说,不可以修改键值,只能修改其对应的实值。map内部数据的组织,map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),这棵树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的。

map接口

1、插入
用insert函数插入pair数据、用insert函数插入value_type数据和用数组方式插入数据

// 用insert函数插入pair数据
#include <map>
#include <string>
#include <iostream>
int main()
{
	std::map<int, std::string> mapStudent;
	mapStudent.insert(pair<int, std::string>(1, "student_one"));
	mapStudent.insert(pair<int, std::string>(2, "student_two"));
	mapStudent.insert(pair<int, std::stirng>(3, "student_three"));
	std::map<int ,std::string>::iterator iter;
	for(iter == mapStudent.begin(); iter != mapStudent.end(); iter++){
		std::cout << iter->first << " " << iter->second << std::endl;
	}
	return 0;
}
// 用insert插入value_type数据
#include <map>
#include <string>
#include <iostream>
int main()
{
	std::map<int, std::string> mapStudent;
	mapStudent.insert(std::map<int, std::string>::value_type(1, "student_one"));
	mapStudent.insert(std::map<int, std::string>::value_type(2, "student_two"));
	mapStudent.insert(std::map<int, std::string>::value_type(3, "student_three"));
	std::map<int ,std::string>::iterator iter;
	for(iter == mapStudent.begin(); iter != mapStudent.end(); iter++){
		std::cout << iter->first << " " << iter->second << std::endl;
	}
	return 0;
}
// 用数组的方式插入数据
#include <map>
#include <string>
#include <iostream>
int main()
{
	std::map<int, string> mapStudent;
	mapStudent[1] = "student_one";
	mapStudent[2] = "student_two";
	mapSutdent[3] = "student_three";
	std::map<int, string>::iterator iter;
	for(iter == mapStudent.begin(); iter != mapStudent.end(); iter++){
		std::cout << iter->first << " " << iter->second << std::endl;
	}
	return 0;
}

2、删除

// 用erase删除map中的元素
#include <map>
#include <string>
#include <iostream>

int main()
{
	std::map<int, std::string> mapStudent;
	mapStudent[1] = "student_one";
	mapStudent[2] = "student_two";
	mapStudent[3] = "student_three";
	mapStudent[4] = "student_four";
	std::map<int, std::string>::iterator iter = mapStudent.begin();
	for(;iter != mapStudent.end();){
		if((*iter).second == "student_one"){
			mapStudent.erase(iter++);
		}else{
			++iter;
		}
	}
	for(iter == mapStudent.begin(); iter != mapStudent.end(); iter++){
		std::cout << iter->first << " " << iter->second << std::endl;
	}
	return 0;
}
// 注意:
// mapStudent.erase(iter++);中的iter++,不是earse(iter),
// 然后iter++。因为iter指针被erase之后就失效了,不能再用iter++;
// 也不是erase(++iter),这样就不是删除iter原来指向的元素了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值