stl中map的基本用法

weixin_33716557發表於2018-05-23
#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;
}

執行結果:


1720840-6ab957cf3e67f9c2.png
執行結果

相關文章