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("呵呵,删没了"));}