#include
map;
pair可以存储两个元素,也被称作“对组”
pair主要的两个成员变量是first和second, first和second可以是任意类型,也可以是自定义的struct类型
1.定义
pairp;
2.函数列表
first () 访问对组的第一个元素。
secend() 访问对组的第二个元素。
make_pair() 生成新的pair对象。
3.创建
pairp=("jack",10);
pairp=make_pair("jack",10);
4.访问
string name=p.first;
int age=p.second;
//1.
mapm;
m[1] = "张三";//相当于定义了一个key为int,value为string的map容器
cout << m[1] << endl;
//2.插入键值对
mapm1;//pair定义了一个键值对,对应 map的key和value
m1.insert(pair("jack", 10));
//3.拷贝
mapm2(m1);
//4.赋值
mapm3;
m3 = m1;
void test1(map& m)//遍历
{
for (map::iterator it = m.begin(); it != m.end(); it++)
{
cout << "key" << (*it).first << " "
<< "value" << (*it).second << endl;
}
}
size
empty
swap
mapm;
m[1] = "张三";
m[2] = "李四";
m[3] = "王五";
cout <<"大小为"<< m.size() << endl;
if (m.empty())cout << "不为空" << endl;
else cout << "为空" << endl;
cout << "交换前 " << m[1] << " " << m[2] << endl;
swap(m[1], m[2]);
cout << "交换后 " << m[1] << " " << m[2] << endl;
mapm;
m[1] = "张三";
m[2] = "李四";
m[3] = "王五";
//1. 使用key删除
m.erase(1);//删除 key = 1的节点
//2. 使用迭代器删除
map::iterator it = m.find(2);
m.erase(it);
//3.全部删除
m.erase(m.begin(), m.end());
//4. 清空整个容器
m.clear();
find(key)
count(key)
//1.
map
m[1] = “张三”;
m[2] = “李四”;
m[3] = “王五”;
map
if (pos != m.end())
cout << “找到了值为 " << pos->first << " 姓名为 " << pos->second << " 的元素” << endl;
else
cout << “该元素不存在” << endl;
//2.
int num = m.count(1);
cout << “key为1的有” << num << “个” << endl;//1.
map
m[1] = “张三”;
m[2] = “李四”;
m[3] = “王五”;
map
if (pos != m.end())
cout << “找到了值为 " << pos->first << " 姓名为 " << pos->second << " 的元素” << endl;
else
cout << “该元素不存在” << endl;
//2.
int num = m.count(1);
cout << “key为1的有” << num << “个” << endl;//1.
map
m[1] = “张三”;
m[2] = “李四”;
m[3] = “王五”;
map
if (pos != m.end())
cout << “找到了值为 " << pos->first << " 姓名为 " << pos->second << " 的元素” << endl;
else
cout << “该元素不存在” << endl;
//2.
int num = m.count(1);
cout << “key为1的有” << num << “个” << endl;//1.
map
m[1] = “张三”;
m[2] = “李四”;
m[3] = “王五”;
map
if (pos != m.end())
cout << “找到了值为 " << pos->first << " 姓名为 " << pos->second << " 的元素” << endl;
else
cout << “该元素不存在” << endl;
//2.
int num = m.count(1);
cout << “key为1的有” << num << “个” << endl;
//1.
mapm;
m[1] = "张三";
m[2] = "李四";
m[3] = "王五";
map::iterator pos = m.find(1);
if (pos != m.end())
cout << "找到了值为 " << pos->first << " 姓名为 " << pos->second << " 的元素" << endl;
else
cout << "该元素不存在" << endl;
//2.
int num = m.count(1);
cout << "key为1的有" << num << "个" << endl;
1.默认按key从小到大
mapm;
m[1] = "张三";
m[2] = "李四";
m[3] = "王五";
for (map::iterator it = m.begin(); it != m.end(); ++it)
cout << it->first << " " << it->second << endl;
2.默认按key从大到小
改为 map>m;
map和mulitimap的区别:
map不允许容器中有相同key值的元素;
multimap允许容器中有相同key值的元素。
#include
#include
#include