以下代码均是MSDN中的代码:
CMap<int,int,CPoint,CPoint> myMap;//指定CMap中码和码值的类型
for (int i=0;i < 10;i++)
myMap.SetAt( i, CPoint(i, i) );//设定码和码值,如果存在相同码,则覆盖
POSITION pos = myMap.GetStartPosition();//得到MAP中码的起始位置,这个位置不能简单认为是0,因为POSION结构不清楚
int nKey;//记录码值,码值和位置值是两个概念
CPoint pt;
/*下面这个循环用来遍历MAP,用pos来控制循环次数,不能认为MAP中码和码值的存放跟其本身没任何关系,
所以不能用计数变量来访问MAP的码值*/
while (pos != NULL)
{
myMap.GetNextAssoc( pos, nKey, pt );//这个函数,pos返回下个码的位置,nKey,pt返回当前pos位置的码,码值
if ((nKey%2) == 0)
myMap.RemoveKey( nKey );//根据码移除码值和码
}
#ifdef _DEBUG
afxDump.SetDepth( 1 );//不清楚作用
afxDump << "myMap: " << &myMap << "/n";
#endif
CMap<int,int,CPoint,CPoint> myMap;
int i;
myMap.InitHashTable( 257);//初始化MAP,无论这里的第二个参数设置为TURE或者FALSE都会动态变化,但初始化表示了让MAP预分配少
//空间
// Add 10 elements to the map.
for (i=0;i < 200;i++)
myMap[i] = CPoint(i, i);//直接根据码来对码给码值
// Remove the elements with even key values.
CPoint pt;
for (i=0; myMap.Lookup( i, pt ) ;i+=2)//lookup根据码来索取码值,码值存放于pt中
{
myMap.RemoveKey( i );//同上
}
#ifdef _DEBUG
ASSERT(myMap.GetCount() == 100);//得到MAP尺寸
afxDump.SetDepth( 1 );
afxDump << "myMap: " << &myMap << "/n";
#endif
说明:1.码相同必然存在覆盖 2.码和码值存放顺序不确定,只能同过上面的while来遍历MAP 3.GetCount函数和GetHashTableSize完全一样 4.码的数据类型必须是基本数据类型,而码值类型不是很确定,没有测试过!