map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道。这里说下map内部数据的组织,map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的。
1,数据的插入
map<int,int> m;
m.insert({1,2});
auto it = m.find(1);
if(it != m.end()){
cout << it->first << " " << it->second;
}
2,map的大小
int msize = m.size();
3,数据的遍历
正向:
map<int,int> m;
int n;cin >> n;
for(int i = 1; i <= n; i++){
cin >> m[i];
}
map<int,int>::iterator it;
for(it = m.begin(); it != m.end(); it++){
cout << it->first << " " << it->second << "\n";
}
反向:
map<int,int> m;
int n;cin >> n;
for(int i = 1; i <= n; i++){
cin >> m[i];
}
map<int,int>::reverse_iterator it;
for(it = m.rbegin(); it != m.rend(); it++){
cout << it->first << " " << it->second << "\n";
}
4,数据的查找
(1)用count函数来判断关键字是否出现,但是无法判断出现位置,count函数的返回值只有0,1,出现返回1。
(2)用find函数来定位数据出现位置,它返回一个迭代器,如果没有找到则返回它的迭代器等于end函数返回的迭代器。
#include <bits/stdc++.h>
using namespace std;
int main()
{
map<int,int> m;
int n;cin >> n;
for(int i = 1; i <= n; i++){
cin >> m[i];
}
cout << m.count(1);
auto it = m.find(1);
if(it != m.end()){
cout << it->first << " " << it->second << "\n";
}
else{
cout << "no find\n";
}
return 0;
}
(3)利用Lower_bound和Upper_bound函数
Lower_bound函数用法,这个函数用来返回要查找关键字的下界(是一个迭代器)
Upper_bound函数用法,这个函数用来返回要查找关键字的上界(是一个迭代器)
例如:map中已经插入了1,2,3,4的话,如果lower_bound(2)的话,返回的2,而upper-bound(2)的话,返回的就是3
#include <bits/stdc++.h>
using namespace std;
int main()
{
map<int,int> m;
int n;cin >> n;
for(int i = 1; i <= n; i++){
cin >> m[i];
}
auto it1 = m.lower_bound(2);
auto it2 = m.upper_bound(2);
cout << it1->first << " " << it1->second << endl;
cout << it2->first << " " << it2->second << endl;
return 0;
5
7 4 2 5 3
2 4
3 2
}
5,数据的清空与判空
清空map中的数据可以用clear()函数,判定map中是否有数据可以用empty()函数,它返回true则说明是空map。
#include <bits/stdc++.h>
using namespace std;
int main()
{
map<int,int> m;
int n;cin >> n;
for(int i = 1; i <= n; i++){
cin >> m[i];
}
auto it = m.find(1);
m.erase(it);//用迭代器删除
int s = m.erase(1);//用关键字删除,删除了会返回1
m.erase(m.begin(),m.end());//删除整个map
return 0;
}