map
#include<iostream>
#include<map>
using namespace std;int main()
{//首先创建一个map对象map<int, char>oneMap;//插入数据oneMap.insert(pair<int, char>(1, 'A'));oneMap.insert(make_pair(2,'B'));oneMap.insert(map<int,char>::value_type(3,'C'));//begin(返回第一个元素的迭代器) end(集合中最后一个元素下一个位置的迭代器) rbegin() rend()for (auto it = oneMap.rbegin(); it != oneMap.rend(); it++){cout << it->first << "->" << (*it).second << endl;}return 0;
}
输出:
判断容器是否为空
if (oneMap.empty())
{cout << "容器为空" << endl;
}
else {cout << "容器不为空" << endl;
}
if语句前加上以下函数,则输出“容器为空”
oneMap.clear();
equal_range(x):返回x的下一个元素的迭代器
cout << (*oneMap.equal_range(2).first).first
<< "->"
<< oneMap.equal_range(2).first->second
<< endl;
输出:
//lower_bound(x) upper_bound(x)返回x元素的迭代器
cout << oneMap.lower_bound(1)->first
<< "->"
<< (*oneMap.upper_bound(1)).second
<< endl;
输出:
//size() max_size()
cout << "当前容量" << oneMap.size() << endl;
cout << "最大容量" << oneMap.max_size() << endl;
输出:
交换:
map<int, char>twoMap;
twoMap.swap(oneMap);
for (auto it = twoMap.begin(); it!=twoMap.end(); it++)
{cout << (*it).first << "->" << it->second << endl;
}
//find(x)--返回x的迭代器
cout << oneMap.find(1)->second << endl;
输出:A
删除:
//erase(x)--删除
oneMap.erase(oneMap.begin());
for (auto it = oneMap.begin(); it!=oneMap.end(); it++)
{cout << it->first << "->" << it->second<<endl;
}
输出: