STL - 容器 - Map(二)

本文演示了如何在C++中使用Map容器作为关联数组来存储股票名称及其价格,并通过示例代码展示了插入元素、修改值、遍历打印、更新键等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

把Map用作关联式数组

MapAdvanceTest.cpp

#include <map>
#include <string>
#include <iostream>
#include <iomanip>
#include "MapAdvanceTest.h"
#include "../../Core/ContainerUtil.h"

using namespace std;

void MapAdvanceTest::useAsAssociativeArray()
{
    // create map / associative array
    // - keys are strings
    // - values are floats
    typedef map<string, float> StringFloatMap;

    StringFloatMap stocks;      // create empty container

    // insert some elements
    stocks["BASF"] = 369.50;
    stocks["VW"] = 413.50;
    stocks["Daimler"] = 819.00;
    stocks["BMW"] = 834.00;
    stocks["Siemens"] = 842.20;

    // print all elements
    ContainerUtil<StringFloatMap>::printMapInDiv(stocks, "Stock", "Price", 15);

    // boom (all prices doubled)
    StringFloatMap::iterator pos;
    for (pos = stocks.begin(); pos != stocks.end(); ++pos) {
        pos->second *= 2;
    }

    // print all elements
    ContainerUtil<StringFloatMap>::printMapInDiv(stocks, "Stock", "Price", 15);

    // rename key from "VW" to "Volkswagen"
    // - provided only by exchanging element
    stocks["Volkswagen"] = stocks["VW"];
    stocks.erase("VW");

    // print all elements
    ContainerUtil<StringFloatMap>::printMapInDiv(stocks, "Stock", "Price", 15);
}

void MapAdvanceTest::run()
{
    printStart("useAsAssociativeArray()");
    useAsAssociativeArray();
    printEnd("useAsAssociativeArray()");
}

运行结果:

---------------- useAsAssociativeArray(): Run Start ----------------
Stock: BASF Price: 369.5
Stock: BMW Price: 834
Stock: Daimler Price: 819
Stock: Siemens Price: 842.2
Stock: VW Price: 413.5

Stock: BASF Price: 739
Stock: BMW Price: 1668
Stock: Daimler Price: 1638
Stock: Siemens Price: 1684.4
Stock: VW Price: 827

Stock: BASF Price: 739
Stock: BMW Price: 1668
Stock: Daimler Price: 1638
Stock: Siemens Price: 1684.4
Stock: Volkswagen Price: 827

---------------- useAsAssociativeArray(): Run End ----------------

转载于:https://www.cnblogs.com/davidgu/p/4936256.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值