#include "stdafx.h"
#include <map>
using namespace std;
struct SPxUserInfo
{
#define MAX_NAME_LEN (512)
unsigned int nUserId;
char szName[MAX_NAME_LEN];
int nAge;
SPxUserInfo()
{
Flush();
}
~SPxUserInfo()
{
Flush();
}
void Flush()
{
nUserId = 0;
memset(szName, 0, MAX_NAME_LEN);
nAge = 0;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
std::map <unsigned int, SPxUserInfo> mapUser;
// 添加数据
SPxUserInfo sPxUserInfo;
sPxUserInfo.nUserId = 1;
strcpy(sPxUserInfo.szName, "Kate");
sPxUserInfo.nAge = 18;
std::map <unsigned int, SPxUserInfo> :: iterator iter = mapUser.find(sPxUserInfo.nUserId);
if (mapUser.end() == iter)
{
mapUser[sPxUserInfo.nUserId] = sPxUserInfo;
}
sPxUserInfo.nUserId = 2;
strcpy(sPxUserInfo.szName, "James");
sPxUserInfo.nAge = 20;
iter = mapUser.find(sPxUserInfo.nUserId);
if (mapUser.end() == iter)
{
mapUser[sPxUserInfo.nUserId] = sPxUserInfo;
}
// 遍历map
printf("遍历map....\n");
iter = mapUser.begin();
while (mapUser.end() != iter)
{
sPxUserInfo = iter->second;
printf("Id: %d, Name: %s, Age: %d\n",
sPxUserInfo.nUserId, sPxUserInfo.szName, sPxUserInfo.nAge);
iter++;
}
printf("遍历结束. 元素个数:%d\n\n", mapUser.size());
// 删除指定元素
int nUserId = 2;
printf("删除nUserId = %d的元素...\n", nUserId);
iter = mapUser.find(nUserId);
if (mapUser.end() != iter) // 如果找到
{
mapUser.erase(iter);
}
iter = mapUser.begin();
while (mapUser.end() != iter)
{
sPxUserInfo = iter->second;
printf("Id: %d, Name: %s, Age: %d\n",
sPxUserInfo.nUserId, sPxUserInfo.szName, sPxUserInfo.nAge);
iter++;
}
printf("删除元素结束.元素个数:%d\n", mapUser.size());
// 判断map是否为空
if (mapUser.empty()) // empty函数: return true only if sequence is empty
{
printf("map is empty\n");
}
else
{
printf("map is not empty\n");
}
printf("\n");
// 清空所有元素
mapUser.clear();
printf("开始清空所有元素...\n");
if (mapUser.empty()) // empty函数: return true only if sequence is empty
{
printf("map is empty\n");
}
else
{
printf("map is not empty\n");
}
getchar();
return 0;
}
运行结果: