1. 定义:
#include<map>
map<int, int>m;
或:
template <class Key, class T,class Pred=less<Key>,
class A = allocator<T> >
class map
{
...
typedef pair<const Key,T> value type;
......
};
- map中的元素都是pair模板类对象。关键字(first成员变量)各不相同。元素按照关键字从小到大排列,缺省情况信息用less,即“<”定义“小于”。
- map里面不能有两个元素的first成员变量的值相同
2. map常用基本操作:
m.clear() //清空map
m.empty() //判断m是否为空
m.begin() //返回指向map头部的迭代器
m.end() //返回指向map末尾的迭代器
m.rbegin() //返回一个指向map尾部的逆向迭代器
m.rend() //返回一个指向map头部的逆向迭代器
m.erase() //删除指定元素
m.find() //查找指定元素
m.insert() //插入元素
m.size() //返回元素的个数
m.swap() //交换两个map
3. map的[ ] 成员函数:
若pairs为map模板类的对象, pairs [ key ]
返回对关键字等于key的元素的值(second成员变量)的引用。若无关键字为key的元素,则会往pairs里插入一个关键字为key的元素,其值永无参构造函数初始化,并返回其值的引用。
如:
map<int,double> pairs;
则
pairs[50]=5; 会修改pairs中关键字为50的元素,使其值变为5;
若不存在关键字等于50的元素,则插入此元素,并使其值变为5
4. map示例:
代码实现如下:
#include<iostream>
#include<map>
using namespace std;
template <class Key, class Value>
ostream & operator << (ostream & o, const pair<Key,Value> & p)
{
o << "(" << p.first << "," << p.second << ")";
return o;
} //输出 pair 对象的内容
int main()
{
typedef map<int, double,less<int> >mmid;
mmid pairs;
cout << "1) " << pairs.count(15) << endl; //pairs内有几个15
pairs.insert(mmid::value_type(15, 2.7)); //插入一个元素进去,元素的first成员变量是15,second成员变量是2.7
pairs.insert(make_pair(15, 99.3)); //make_pair生成一个pair对象
cout << "2) " << pairs.count(15) << endl;
pairs.insert(mmid::value_type(20, 9.3));
mmid::iterator i;
cout << "3) ";
for(i=pairs.begin(); i!=pairs.end(); i++)
{
cout << *i << ",";
}cout << endl;
cout << "4) ";
int n=pairs[40]; //如果没有关键字为40的元素,则插入一个
for(i=pairs.begin(); i!=pairs.end(); i++)
{
cout << *i << ",";
}cout << endl;
cout << "5) ";
pairs[15]=6.28; //把关键字为15的元素值改为6.28
for(i=pairs.begin(); i!=pairs.end(); i++)
{
cout << *i << ",";
}cout << endl;
return 0;
}
运行结果: