CMap使用方法總結


#include <array>

#ifdef _DEBUG
#include <iostream>
#include <fstream>
using std::endl;
#endif

void CMFCApplication1Dlg::OnBnClickedOk()
{
	// TODO: 在此添加控件通知處理程序代碼
#ifdef _DEBUG
	std::ofstream  ofs("log.txt");
#endif
	
	// 使用SetAt()初始化
	typedef CMap<CString, CString, CString, CString> MAP_EMPLOYEE;
	MAP_EMPLOYEE map_employee;
	std::array<CString, 3> employee_id{"100","108","120"};
	std::array<CString, 3>employee_name{_T("shihuan"), _T("lipeng"), _T("tianjunhong")};
	for (auto i=0; i!=employee_id.size(); ++i)
	{
		map_employee.SetAt(employee_id[i], employee_name[i]);
	}
	
	// 使用POS遍歷
	POSITION pos = map_employee.GetStartPosition();
	while (pos)
	{
		CString key = 0;
		CString value;
		map_employee.GetNextAssoc(pos, key, value);
#ifdef _DEBUG
		ofs << key.GetString() << " " << value.GetString() << endl;
#endif
	}

	// 使用CPair* 遍歷
	auto p = map_employee.PGetFirstAssoc();
	while (p != NULL)
	{
#ifdef _DEBUG
		ofs << p->key.GetString() << " " << p->value.GetString() << endl;
#endif
		p = map_employee.PGetNextAssoc(p);
	}

#ifdef _DEBUG
	ofs.close();
#endif

	CString value;
	BOOL ret;
	ret = map_employee.Lookup("100", value);   // 查找:未找到返回0
	assert(0 == ret);
	ret = map_employee.RemoveKey("100");       // 刪除:不存在返回0
	ASSERT(0 != ret);
	map_employee.RemoveAll();                // 清空

	CDialogEx::OnOK();
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM