目录
1.map的构造和赋值
2.map的大小和交换
3.map的插入和删除
4.map的查找和统计
5.map的排序
1.map的构造和赋值
#include<bits/stdc++.h>
using namespace std;
void print(map<int,int> &mp)
{
for(map<int,int>::iterator it = mp.begin(); it != mp.end(); it++)
{
cout << it -> first << ' ' << it -> second;
cout << endl;
}
cout << endl;
}
int main()
{
map<int,int> mp;
mp.insert(pair<int,int>(1,90));
mp.insert(pair<int,int>(2,950));
mp.insert(pair<int,int>(7,920));
mp.insert(pair<int,int>(5,10));
mp.insert(pair<int,int>(6,80));
//按照key的值进行排序
print(mp);
return 0;
}
2.map的大小和交换
#include<bits/stdc++.h>
using namespace std;
void print(map<int,int> &mp)
{
for(map<int,int>::iterator it = mp.begin(); it != mp.end(); it++)
{
cout << it -> first << ' ' << it -> second;
cout << endl;
}
cout << endl;
}
int main()
{
map<int,int> mp;
mp.insert(pair<int,int>(1,90));
mp.insert(pair<int,int>(2,950));
mp.insert(pair<int,int>(7,920));
mp.insert(pair<int,int>(5,10));
mp.insert(pair<int,int>(6,80));
//按照key的值进行排序
print(mp);
cout << mp.empty() << endl;
cout << mp.size() << endl;
map<int,int>mp1;
mp1.swap(mp);
print(mp1);
return 0;
}
3.map的插入和删除
#include<bits/stdc++.h>
using namespace std;
void print(map<int,int> &mp)
{
for(map<int,int>::iterator it = mp.begin(); it != mp.end(); it++)
{
cout << it -> first << ' ' << it -> second;
cout << endl;
}
cout << endl;
}
int main()
{
map<int,int> mp;
mp.insert(pair<int,int>(1,90));
mp.insert(pair<int,int>(2,950));
mp.insert(make_pair(7,920));
mp.insert(pair<int,int>(5,10));
mp[6] = 80;
//按照key的值进行排序
print(mp);
mp.erase(6);
//按照key删除
mp.erase(mp.begin());
//也可以传迭代器进行删除
print(mp);
mp.clear();
print(mp);
return 0;
}
4.map的查找和统计
#include<bits/stdc++.h>
using namespace std;
void print(map<int,int> &mp)
{
for(map<int,int>::iterator it = mp.begin(); it != mp.end(); it++)
{
cout << it -> first << ' ' << it -> second;
cout << endl;
}
cout << endl;
}
int main()
{
map<int,int> mp;
mp.insert(pair<int,int>(1,90));
mp.insert(pair<int,int>(2,950));
mp.insert(make_pair(7,920));
mp.insert(pair<int,int>(5,10));
mp[6] = 80;
map<int,int>::iterator it = mp.find(5);
//从前往后找map里有没有key为5的,没找到的话迭代器就在mp.end()处
if(it != mp.end()) cout << "找到了" << endl;
cout << mp.count(7) << endl;
//输出有几个key为7的数,这里只有一个
return 0;
}
5.map的排序
改成从大到小
#include<bits/stdc++.h>
using namespace std;
class cmp
{
public:
bool operator()(int v1,int v2)
{
return v1 > v2;
}
};
int main()
{
map<int,int,cmp> mp;
mp.insert(pair<int,int>(1,90));
mp.insert(pair<int,int>(2,950));
mp.insert(make_pair(7,920));
mp.insert(pair<int,int>(5,10));
mp[6] = 80;
for(map<int,int,cmp>::iterator it = mp.begin(); it != mp.end(); it++)
{
cout << it -> first << ' ' << it -> second << endl;
}
return 0;
}