赞
踩
map 经常会被面试问到相关的基本操作;
#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; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。