c++ 基础练习

2019-10-18  本文已影响0人  eleven_a1dc

map demo

#include <iostream>
#include <string>
#include <map>
using namespace std;

map<int, string> Id_Names;
int main(){

Id_Names = {
    {2015, "Jim"},
    {2016, "Tom"},
    {2018,"Alex"}
}; // 初始化

Id_Names[2020] = "JIM"; // 添加元素
cout << Id_Names.size() << endl;// 打印长度
auto res = Id_Names.insert(pair<int,string>(2018,"Daiwei"));
auto res2 = Id_Names.insert(pair<int,string>(2022,"Daiwei"));// 插入
// 判断插入结果
if (res.second == false) {
cout << "insert res eaild" << endl;
}

if(res2.second == false) {
cout << "insert res2 failed" << endl;

}
cout << Id_Names[2022] << endl;
cout << Id_Names.at(2016) << endl;// at 会做下标检查,不存在会报错
if(Id_Names.empty()){
cout << "Map is Empty"<< endl;
return 1;
}
if(Id_Names.count(2015)==1){
cout << "has key 2015" << endl;
}
Id_Names.erase(2015);// 删除key 返回值为0或1
if(Id_Names.count(2015)==0){
cout << "not has key 2015" << endl;
}
for(auto m: Id_Names) {
cout << "Key: " << m.first << endl;
cout << "Value: " << m.second << endl;

}
Id_Names.clear();// 清空map
cout << Id_Names.size() << endl;
return 0;
}
上一篇下一篇

猜你喜欢

热点阅读