C++ STL : std::map



练习下C++ STL中std::map类的常用方法,方便以后查阅。

如有不正确的地方,请读者及时指正,欢迎转载,谢谢!

#include <map>

//std::map是最常用的关联容器,类模板,使用<key,value>键值对的形式来存储和查询数据,其底层通过红黑树(一种平衡二叉树)来实现。
//std::map访问和查找速度非常快,时间复杂度是log(n);还有一种更快的std::hash_map底层是用hash表存储的,查询时间复杂度是O(1),但是占用空间较大。
//如果只存储唯一的key,不需要value,那么可以使用std::set容器。

class Date
{
public:
	Date(int s, int t) : m_month(s), m_day(t) 
	{
	}

	bool operator < (const Date &d) const							//注意必须是const函数
	{
		//return (m_month < d.m_month || m_day < d.m_day);		//注意这样写是错误的
		return m_month < d.m_month || (m_month == d.m_month && m_day < d.m_day);
	}
	
private:
	int m_month;
	int m_day;
};

struct Comp
{
	typedef std::pair<int, int> value_type;
	bool operator () (const value_type & ls, const value_type &rs)
	{
		return ls.first < rs.first || (ls.first == rs.first && ls.second < rs.second);
	}
};


inline void testMap() 
{		
	std::map<int,std::string> vmap;

	//插入map
	vmap[0] = "test0";
	vmap[7] = "test7";
	vmap.insert(std::make_pair(11,"test11"));
	vmap.insert(std::map<int, std::string>::value_type(12,"test12"));

	//查找map
	auto iter1 = vmap.find(7);
	std::map<int,std::string>::const_iterator iter2 = vmap.find(7);

	//删除map
	if (iter2 != vmap.end())
	{
		vmap.erase(iter2);
	}
	
	//遍历map
	for (auto iter3 = vmap.begin(); iter3 != vmap.end(); iter3++)
	{
		printf("key=%d \n",iter3->first);
		printf("key=%s \n",iter3->second.c_str());
	}

	//增加或删除map元素会使迭代器失效,解决方法:
	for (auto iter4 = vmap.begin(); iter4 != vmap.end(); )
	{
		if (iter4->first == 11)
		{
			vmap.erase(iter4++);
		}
		else
		{
			iter4++;
		}
	}

	//map自定义key, 有两种方法: 
	//1)重载< 自定义key
	Date key1(1,2);
	Date key2(2,1);
	Date key3(1,3);
	Date key4(3,2);
	Date key5(2,2);
	Date key6(2,3);
 	std::map<Date,std::string> dateMap;
 
	dateMap[key1] = "key1";
 	dateMap[key2] = "key2";
	dateMap[key3] = "key3";
	dateMap[key4] = "key4";
	dateMap[key5] = "key5";
	dateMap[key6] = "key6";
	
	//2)自定义一个类作为仿函数,传给map第三个参数,std::map默认的仿函数为std::less
	Comp::value_type com1(1,2);
	Comp::value_type com2(2,1);
	Comp::value_type com3(1,1);
	std::map<Comp::value_type,std::string,Comp> compMap;

	compMap[com1] = "com1";
	compMap[com2] = "com2";
	compMap[com3] = "com3";

	return;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值