map/multimap容器中所有的元素都是pair,即对组。pair中的第一个值为key值,第二个值为value实值。所有元素都会根据key值进行默认的升序排序。
map容器的优点在于可以根据key值快速地找到value值。在map容器中,不允许有重复的key值;而在multimap中是允许的。
一、基本语法
#include<iostream>
#include<map>
using namespace std;
int main()
{
//第一种常用构造方法
map<int, int> m;
m.insert(pair<int, int>(1, 10));
//第二种常用构造方法
m.insert(make_pair(2, 20));
//第三种
m[3] = 30;
//读数据,传入的是key值
cout << m[3] << endl << endl;
//打印容器中所有的值
for (map<int, int>::iterator i = m.begin(); i != m.end(); i++)
{
cout << "key: " << (*i).first << ' ' << "value: " << (*i).second << endl;
}
cout << endl;
//用find函数查找容器中的值,传入的是key值或者迭代器,返回的是迭代器
cout << "The 2nd number is " << (*m.find(2)).second << endl;
cout << endl;
//删除容器中的值,传入的是迭代器或者key值
//删除容器开头的数
m.erase(m.begin());
for (map<int, int>::iterator i = m.begin(); i != m.end(); i++)
{
cout << "key: " << (*i).first << ' ' << "value: " << (*i).second << endl;
}
cout << endl;
//删除key值为3的数
m.erase(3);
for (map<int, int>::iterator i = m.begin(); i != m.end(); i++)
{
cout << "key: " << (*i).first << ' ' << "value: " << (*i).second << endl;
}
cout << endl;
system("pause");
}
运行结果:
30
key: 1 value: 10
key: 2 value: 20
key: 3 value: 30
The 2nd number is 20
key: 2 value: 20
key: 3 value: 30
key: 2 value: 20
请按任意键继续. . .
二、对map容器中的元素进行降序排序
方法与对set容器进行降序排序的操作基本相同
#include<iostream>
#include<map>
using namespace std;
class func
{
public:
bool operator()(const int num1, const int num2)
{
return num1 > num2;
}
};
int main()
{
map<int, int, func> m;
m.insert(pair<int, int>(1, 10));
m.insert(make_pair(2, 20));
m[3] = 30;
for (map<int, int, func>::iterator i = m.begin(); i != m.end(); i++)
{
cout << "key: " << (*i).first << ' ' << "value: " << (*i).second << endl;
}
cout << endl;
system("pause");
}
运行结果:
key: 3 value: 30
key: 2 value: 20
key: 1 value: 10
请按任意键继续. . .