【C++】Map类学习

Map类操作详解:添加、查找、遍历与清除
本文详细介绍了Map类的基本操作,包括添加数据、根据键搜索值、使用迭代器遍历、删除键值对及清空操作。通过三种添加方式展示Map的灵活性,并演示了如何遍历Map中的键值对,以及如何使用erase和clear函数进行键值对的删除和Map的清空。

1.关于本文

文中描述的是一个学习Map类过程中写的程序,程序中进行了以下步骤

1)建立map<string, string>

2)为map添加数据(三种方式)

3)根据键搜索出对应值

4)使用迭代器遍历map

5)使用erase函数删除键值对

6)使用clear函数清空map中的键值对,使用size函数查看map大小

2.程序代码

#include <iostream>
#include <map>

using namespace std;

int main()
{
    cout << "Program Activate!" << endl << endl;

    map<string, string> mapNameList;

    // Add Data
    cout << "Add Data!" << endl;
    // Method [1]
    mapNameList.insert(pair<string, string>("101", "Tsybius"));    
    mapNameList.insert(pair<string, string>("102", "Galatea"));
    mapNameList.insert(pair<string, string>("105", "Lepidus"));
    mapNameList.insert(pair<string, string>("104", "Octavius"));
    mapNameList.insert(pair<string, string>("103", "Antonius"));
    // Method [2]
    mapNameList.insert(map<string, string> :: value_type("106", "Atia"));
    // Method [3]
    mapNameList["107"] = "Servilia";
    cout << endl;

    // Output Values 
    cout << "Find Keys " << endl;
    cout << "102: " << mapNameList["102"] << endl;
    cout << "108: " << mapNameList["108"] << endl;
    cout << endl;

    // Traverse Map
    cout << "Traverse Map" << endl;
    map<string, string> :: iterator iter;
    for(iter = mapNameList.begin(); iter != mapNameList.end(); iter++)
    {
        cout << iter -> first << " 's value is " << iter -> second << endl;
    }
    cout << endl;

    // Erase Key
    cout << "Erase Key 104 & 107" << endl;
    mapNameList.erase("104");
    mapNameList.erase(mapNameList.find("105"));
    cout << endl;

    // Traverse Map
    cout << "Traverse Mag Again!" << endl;
    for(iter = mapNameList.begin(); iter != mapNameList.end(); iter++)
    {
        cout << iter -> first << "'s value is " << iter -> second << endl;
    }
    cout << endl;

    // Clear Map
    cout << "Count of pairs: " << mapNameList.size() << endl;
    mapNameList.clear();
    cout << "Map Cleared!" << endl;
    cout << "Count of pairs: " << mapNameList.size() << endl << endl;

    cout << "Program Closed" << endl;

    return 0;
}

3.makefile文件

a: a.o
    g++ -o a a.o
a.o: a.cpp
    g++ -c a.cpp
clean:
    rm -rf *.o a

4.运行结果

193708_ujwz_1425762.png

END

转载于:https://my.oschina.net/Tsybius2014/blog/292634

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值