MFC CMap使用总结

CMap中的操作函数简介

Lookup:查找与指定关键码对应的值

SetAt:在映射中插入一个元素,如果发现相匹配的关键码,则替换已经存在的元素

Operator[]:在映射中插入一个元素,它是代替SetAt的操作符

RemoveKey:删除关键码指定的元素

RemoveAll:删除映射中所有的元素

GetStartPosition:返回第一个元素的位置

GetNextAssoc:获取循环中的下一个元素

GetHashTableSize:获取散列表的大小(元素的个数)

InitHashTable:初始化散列表,并指定其大小

状态:

GetCount:返回Map中元素的数目

IsEmpty:检查Map是否为空(即字典中无元素单元)

//1.创建CMap

//friend class CMap<KEY,ARG_KEY,VALUE,ARG_VALUE>; //CMap原始定义
CMap<int, int, CString, CString> mapName;
CString sName = _T("");
int sScore = 0;
for (int i = 0; i < 5; i++)
{
sName.Format(_T("name_%d"), i);
mapName.SetAt(i, sName);
}

CMap<CString, LPCTSTR, CString, LPCTSTR> my_Map;
CString strKey = _T(""), strValue = _T("");
for (int i = 0; i<5; i++)
{
strKey.Format(_T("%d"), i);
strValue.Format(_T("V%d"), i);
my_Map.SetAt(strKey, strValue);
}

//2.遍历

POSITION po = mapName.GetStartPosition();
while (po)
{
mapName.GetNextAssoc(po, sScore, sName);
AfxMessageBox(sName);
}

//3.根据键查找值

CString sLook = _T("");
if (my_Map.Lookup(_T("2"), sLook))
{
AfxMessageBox(sLook);
}

if (!my_Map.IsEmpty()) //4.判断集合是否为空
{
int n = my_Map.GetCount(); //5.获取集合中的项的个数
CString str = _T("");
str.Format(_T("%d"), n);
AfxMessageBox(str);
}

if (my_Map.RemoveKey(_T("2"))) //6.根据键删除项
{

AfxMessageBox(_T("呵呵,删除了键值为2的项"));
int n = my_Map.GetCount();
CString str = _T("");
str.Format(_T("%d"), n);
AfxMessageBox(str);
}

my_Map.RemoveAll(); //7.移除集合中所有的项(元素)
if (my_Map.IsEmpty())
{
AfxMessageBox(_T("呵呵,删没了"));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值