标准模板库(STL)使用说明 之 7 map

STL(standard template library)是一个具有工业强度的高效C++程序库。它被容纳于C++标准程序库(C++ Standard Library)中,是ANSI/ISO C++标准中最新的也是极具革命性的一部分。该库包含了诸多在计算机科学领域里所常用的基本数据结构和基本算法。为广大C++程序员们提供了一个可扩展的应用框架,高度体现了软件的可复用性。
常见的容器主要有 vector,string,deque,pari,set,multiset,map,multimap 8种。
本文介绍: 

  • 映射 map
    • 初始化
    • 插入操作
    • 删除和查找
//初始化
//map容器的模板参数 需要指定key类型  value类型
map<int, string> mymap; //默认构造
map<int, string> mymap2(mymap); //拷贝构造
//插入操作
map<int, int> mymap;

//第一种插入方式
mymap.insert(pair<int, int>(1, 5));
//第二种
pair<map<int, int>::iterator, bool> ret = mymap.insert(make_pair(2, 10));
if (ret.second){
    cout << "插入成功!" << endl;
}
else{
cout << "插入失败!" << endl;
}
//第三种
mymap.insert(map<int, int>::value_type(3,15));
//第四种,有则修改,无则添加
mymap[4] = 20;  
//删除和查找
map<int, int> mymap;
mymap.insert(make_pair(1, 2));
mymap.insert(make_pair(2, 3));
mymap.insert(make_pair(3, 4));
mymap.erase(2);  //根据Key删除元素
print(mymap);
mymap.erase(mymap.begin()); //删除第一个元素
print(mymap);
mymap.erase(mymap.begin(),mymap.end()); // mymap.clear
cout << "map size:" << mymap.size() << endl;

//查找
map<int, int>::iterator pos =  mymap.find(3);
if (pos == mymap.end()){
    cout << "没有找到!" << endl;
}
else{
cout << "查找到:" << pos->first << " value:" << pos->second << endl;
}

cout << "---------------" << endl;
pos =  mymap.lower_bound(2);
if (pos == mymap.end()){
    cout << "没有找到!" << endl;
}
else{
cout << "查找到:" << pos->first << " value:" << pos->second << endl;
}

pos = mymap.upper_bound(2);
if (pos == mymap.end()){
    cout << "没有找到!" << endl;
}
else{
cout << "查找到:" << pos->first << " value:" << pos->second << endl;
}

pair<map<int, int>::iterator, map<int, int>::iterator> pos2 = mymap.equal_range(2);
if (pos2.first == mymap.end()){  //第一个迭代器
    cout << "没有找到!" << endl;
}
else{
cout << "查找到:" << pos2.first->first << " value:" << pos2.first->second << endl;
}

if (pos2.second == mymap.end()){ //第二个迭代器
    cout << "没有找到!" << endl;
}
else{
cout << "查找到:" << pos2.second->first << " value:" << pos2.second->second << endl;
}
  •  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

giantmfc123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值