CMap使用方法总结

时间:2023-03-09 12:58:32
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();
}