C++ map 插入元素,删除元素

map 经常会被面试问到相关的基本操作;

  1. 遍历过程删除map的元素是会导致当前绑定到map变量的 iterator 失效,继续使用迭代器会崩溃
  2. 使用新的缓存map , 复制原来的map,跳过需要删除的那个
  3. 正常情况下使用 map 的 erase(【下标key】) 删除,或者
  4. 添加元素,使用类似数组的方式,或者使用 insert(std::make_pair(key, val))
#ifndef CPPLEAR_H
#define CPPLEAR_H
#include <map>
using namespace std;

class Cpplear
{
public:
    Cpplear();

    void testMap();

//    template <class 类型参数1, class类型参数2, ...>
//    返回值类型  模板名(形参表)
//    {
//        函数体
//    }


    template <class Tkey, class Tval>
    void printMap(std::map<Tkey, Tval> mapInput) ;
};

#endif // CPPLEAR_H

#include "cpplear.h"
#include <iostream>
#include <QDebug>

Cpplear::Cpplear()
{

}

void Cpplear::testMap()
{
    std::map<string, int> mapAge;
    mapAge["Mike"] = 17;                             // 初始化map节点
    mapAge["Lucy"] = 20;
    mapAge["Jane"] = 18;
    mapAge["kaite"] = 16;
    mapAge.insert(std::make_pair("aaa", 12));       // 插入一个节点元素
    printMap(mapAge);
    mapAge.erase("Jane");

    std::map<int, int> mapId;
    mapId.insert(std::make_pair(0, 99));
    mapId.insert(std::make_pair(1, 100));
    printMap(mapId);

    // 循环中删除一个元素
    std::map<string, int> mapAgeNew;              // 准备一个缓存map
    std::map<string, int>::iterator it = mapAge.begin();
    while (it != mapAge.end()) {
        cout << it->first << ",age="  << it->second << endl;
        if(it->first == "Lucy") {               // OK
            it++;
            continue;
        }
        mapAgeNew[it->first] = it->second;
        it++;
    }
    qDebug() << "delete one note" ;
    printMap(mapAgeNew);
    // auto 关键字遍历,按照下标顺序输出
    for (auto it: mapAge) {
        std::cout << it.first <<"," << it.second << std::endl;

        if (it.first == "Mike") {
//            mapAge.erase(it.first);         // NG, 崩溃
        }
    }
}

template<class Tkey, class Tval>
void Cpplear::printMap(std::map<Tkey, Tval> mapInput)
{
    std::cout << "****************  result ****************" <<std::endl;

    // 迭代器遍历
//    std::map<Tkey, Tval>::iterator it = mapInput.begin();
//    while (it != mapInput.end()) {
//        cout << it->first << ",age="  << it->second << endl;
//        it++;
//    }

    // auto 关键字遍历,按照下标顺序输出
    for (auto it: mapInput) {
        std::cout << it.first <<"," << it.second << std::endl;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值