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

版权声明:请注明转发出处 https://blog.csdn.net/mafucun1988/article/details/89630968

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;
}
  •  

猜你喜欢

转载自blog.csdn.net/mafucun1988/article/details/89630968