zoukankan      html  css  js  c++  java
  • STL

    把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 ----------------

  • 相关阅读:
    谈谈焦虑
    Bridge
    Abstract Factory
    开篇辞
    缓存穿透和缓存雪崩
    缓存与数据库的一致性思考
    GDB
    代码格式化
    CSMA/CA协议
    18年秋招(19届)复习指导+面经总结,手把手教你进大厂——阿里、网易、京东、多益等
  • 原文地址:https://www.cnblogs.com/davidgu/p/4936256.html
Copyright © 2011-2022 走看看