⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mapexample.cpp

📁 MFC 函数实用手册 MFC 函数实用手册
💻 CPP
字号:
// MapExample.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "MapExample.h"
#include "afxtempl.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 唯一的应用程序对象

CWinApp theApp;

using namespace std;

class CMyClass
{
public:
	int nValue;
	CMyClass()
	{
	}
	CMyClass(int value)
	{
		nValue = value;
	}
	void Print(const char* str)
	{
		printf(str);
	}
};

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;

	// 初始化 MFC 并在失败时显示错误
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		// TODO: 更改错误代码以符合您的需要
		_tprintf(_T("致命错误:MFC 初始化失败\n"));
		nRetCode = 1;
	}
	else
	{
		// TODO: 在此处为应用程序的行为编写代码。

		// 构造一个保存CMyClass对象的映射对象
		typedef CMap<int, int, CMyClass, CMyClass> MyMap;
		MyMap myMap;
		// 初始化散列表入口个数
		myMap.InitHashTable(10);
		printf("散列表的大小为:%d。\n",myMap.GetHashTableSize());
		// 向映射中插入元素
		for (int i=0;i < 10;i++)
			myMap.SetAt(i,CMyClass(i+1));
			/* 
			也可以使用以下方法:
			myMap[i] = CMyClass(i+1);
			*/

		if( !myMap.IsEmpty() )
		{
			// 定义一个镶套的结构,包含当前键值下相应的对象
			// 要求用typedef定义CMap<int, int, CMyClass, CMyClass>
			MyMap::CPair* pCurValue;
			// 获得第一个元素的指针。
			pCurValue = myMap.PGetFirstAssoc();
			while (pCurValue != NULL)
			{
				printf("当前键值为:%d,值为:%d。\n", pCurValue->key, pCurValue->value.nValue);
				// 获得下一个元素的指针
				pCurValue = myMap.PGetNextAssoc(pCurValue);
			}
			/*
			可以使用以下方法实现以上功能
			POSITION pos = myMap.GetStartPosition();
			int nKey;
			CMyClass myClass;
			while(pos != 0)
			{
				myMap.GetNextAssoc(pos,nKey,myClass);
				printf("当前键值为:%d,数值为:%d。\n", nKey, myClass.nValue);
			}
			int n = 3;
			CMyClass myClass;
			if(myMap.Lookup(n, myClass))
			{
				printf("键值为 %d 的元素的值为:%d。\n",n,myClass.nValue);
			}
			printf("当前散列表的大小为:%d。\n", myMap.GetHashTableSize());
			*/
			int n = 3;
			if( (pCurValue = myMap.PLookup(n)) != NULL )
				// 如果指定元素存在则移除该元素
				myMap.RemoveKey(pCurValue->key);
			printf("移除键值为三的元素后映射中元素的个数为:%d。\n" ,myMap.GetCount());
			myMap.RemoveAll();
			printf("调用RemoveAll函数后映射中元素的个数为:%d。\n" ,myMap.GetSize());
		}
		
		getchar();
	}

	return nRetCode;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -