STL - 容器 - Map(一)

本文详细介绍了使用C++标准库中的map容器进行元素插入、遍历及修改的方法。通过具体的代码示例,展示了如何利用范围for循环和迭代器进行元素遍历,以及如何使用lambda表达式对元素值进行平方运算。

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

MapTest.cpp

#include <map>
#include <string>
#include <iostream>
#include <algorithm>
#include "MapTest.h"

using namespace std;

void MapTest::simpleEnumeration()
{
    map<string,double> coll { 
        { "tim", 9.9 },                          
        { "struppi", 11.77 }
    } ;

    // for range-based enumeration
    cout << "for range-based enumeration: " << endl;
    for (auto elem : coll)
    {
        cout << elem.first << ": " << elem.second << endl;
    }

    // iterating
    cout << "iterating: " << endl;
    map<string, double>::iterator pos;
    for (pos = coll.begin(); pos != coll.end(); ++pos)
    {
        cout << pos->first << ": " << pos->second << endl;
    }

    // square the value of each element:
    for_each (coll.begin(), coll.end(),
              [] (pair<const string,double>& elem) {
                    elem.second *= elem.second;
              });

    // print each element:
    cout << "for_each lambda enumeration: " << endl;
    for_each (coll.begin(), coll.end(),
              [] (const map<string,double>::value_type& elem) {
                    cout << elem.first << ": " << elem.second << endl;
              });
}

void MapTest::run()
{
    printStart("simpleEnumeration()");
    simpleEnumeration();
    printEnd("simpleEnumeration()");
}

运行结果:

--------------- simpleEnumeration(): Run Start ----------------
for range-based enumeration:
truppi: 11.77
im: 9.9
terating:
truppi: 11.77
im: 9.9
or_each lambda enumeration:
truppi: 138.533
im: 98.01
--------------- simpleEnumeration(): Run End ----------------

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值