CMap 映射表的学习笔记

CList CMap CArray 是MFC 封装的一个模板类,除了可以使用原子类型 如int当作参数以外,还可以使用编码人员自定义的结构体或者类对象当作传入传出参数,

然而MFC还提供了很多CMapWordToPtr 等基于指定数据类型的非模版类。

CMap <int , int , CString , LPCTSTR/*CString*/> mapString; //mapString(int) 默认大小为10 
	                                                                      //CString 使用LPCTSTR当作传入参数 是因为MFC实现了 T通用类型
	                                                                      //其实使用CString 或者LPCTSTR是一样的 他会根据工程编码而改变 VS2008是这的	                                                                      //*CString 并不是C++的原子类型(如int ...) 他是一个有构造函数的类
	
	//判断是否为空
	BOOL bRet = mapString.IsEmpty();

	//初始化Hash表大小 *奇怪的是表的大小居然跟插入元素个数没有关系,不解
	mapString.InitHashTable(10);

	//查询Hash表元素个数 
	int nHash = mapString.GetHashTableSize();

	//遍历映射表插入数据
	int Index = 0;
	CString strText;
	for (Index = 0; Index < 100; Index++)
	{
		strText.Format(_T("the number is: %d"),Index);
		mapString.SetAt(Index,strText);
	}

	//查询总数
	int nCount = mapString.GetCount();

	//查询Hash表元素个数 
	nHash = mapString.GetHashTableSize();

	//使用Lookup函数 提供Key值 返回对应的数据
	strText.Empty(); //初始化strText
	mapString.Lookup(10,strText);

	//使用RemoveKey函数索引为 n 的数据
	mapString.RemoveKey(10);

	//再次查找数据 肯定就没有了 cmap也是类似于clist的链表数据结构
	strText.Empty();
	mapString.Lookup(10,strText);

	//遍历映射表方法
	POSITION pi = mapString.GetStartPosition();
	while (pi != NULL)
	{
		int nKey = 0;
		strText.Empty();//GetNextAssoc 三个参数均是传值调用参数
		mapString.GetNextAssoc(pi,nKey,strText);
	}

	//使用SetAt 修改索引值为 n 的数据
	mapString.SetAt(5,_T("modify data"));

	//遍历查找对应的数据 返回对应的Key
	pi = mapString.GetStartPosition();
	strText = _T("the number is: 11");
	for(;pi != NULL;)
	{
		CString strTemp;
		int nKey = 0;
		mapString.GetNextAssoc(pi,nKey,strTemp);
		if (strTemp == strText)
		{
			int nSuccess = nKey;
			break;
		}
	}

	//移除所有数据
	mapString.RemoveAll();

初次接触CMAP类,顺便也请教下大神,关于哈希表的大小跟元素个数到底有什么关系,看MSDN介绍,是返回元素的个数,

但是使用的过程中并不是这样,望大神指点下。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值