1-map的使用.cpp
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<int, string> m; //key是int类型 value是string类型
m.insert(pair<int, string>(3, "aa")); //通过pair对组(组合一组数据)插入
m.insert(pair<int, string>(1, "zz"));
m.insert(make_pair(5, "cc")); //通过make_pair组合一对数据插入
m.insert(make_pair(4, "ff"));
m.insert(map<int, string>::value_type(6, "hh")); //通过map内部静态成员函数插入
m.insert(map<int, string>::value_type(2, "dd"));
m[8] = "uu"; //map重载了[]运算符
m[7] = "ee";
//遍历结果 按照key自动排序
for (map<int, string>::iterator it = m.begin(); it != m.end(); it++)
{
//it指向map的一个结点,一个结点就是一个pair对象,即it指向pair对象,pair对象有两个成员,first和second
cout << "学号 " << it->first << " 姓名 " << it->second << endl;
}
//前三种插入方法,如果数据已经存在则返回错误;第四种方法,如果数据存在则覆盖
pair<map<int, string>::iterator, bool> p = m.insert(make_pair(5, "qq"));
if (p.second == false)
{
cout << "插入失败" << endl; //返回的迭代器指向已经存在的结点
cout << "学号 " << p.first->first << " 姓名 " << p.first->second << endl;
}
else
{
cout << "插入成功" << endl;
}
m[3] = "www"; //直接把原有的数据覆盖
for (map<int, string>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "学号 " << it->first << " 姓名 " << it->second << endl;
}
cout << "map删除指定的位置" << endl;
m.erase(m.begin());
for (map<int, string>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "学号 " << it->first << " 姓名 " << it->second << endl;
}
cout << "map删除区间" << endl;
m.erase(--(m.end()), m.end());
for (map<int, string>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "学号 " << it->first << " 姓名 " << it->second << endl;
}
cout << "map删除具体元素" << endl;
m.erase(4); //根据k值删除
for (map<int, string>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "学号 " << it->first << " 姓名 " << it->second << endl;
}
return 0;
}
2-multimap.cpp
#include <iostream>
#include <map>
using namespace std;
class Employee
{
private:
int id;
string name;
public:
Employee(int i, string n)
{
id = i;
name = n;
}
void show()
{
cout << "工号:" << id << " 姓名:" << name << endl;
}
};
int main()
{
Employee e1(1, "aa");
Employee e2(2, "aa");
Employee e3(3, "aa");
Employee e4(4, "aa");
Employee e5(5, "aa");
Employee e6(6, "aa");
Employee e7(7, "aa");
Employee e8(8, "aa");
multimap<string, Employee> m;
//销售部门有三个员工
m.insert(make_pair("sale", e1));
m.insert(make_pair("sale", e2));
m.insert(make_pair("sale", e3));
//研发部门一个员工
m.insert(make_pair("development", e4));
//财务部门4个员工
m.insert(make_pair("financial", e5));
m.insert(make_pair("financial", e6));
m.insert(make_pair("financial", e7));
m.insert(make_pair("financial", e8));
cout << m.count("financial") << endl;
for (multimap<string, Employee>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "部门:" << it->first << endl;
it->second.show();
}
return 0;
}