#include<map>
#include<string>
#include<iostream>
using namespace std;
void printFun(map<int, string> &obj)
{
for (map<int, string>::iterator it = obj.begin(); it != obj.end(); it++)
{
cout << it->first << " " << it->second << endl;
}
cout << endl;
}
int main()
{
map<int,string> map1;
//方法1
map1.insert(pair<int, string>(1, "stu1"));
//方法2
map1.insert(make_pair(2, "stu2"));
//方法3
map1.insert(map<int, string>::value_type(3, "stu3"));
//方法4
map1[4] = "stu4";;
map1[6] = "stu6";
map1[0] = "stu0";
printFun(map1);
//判断插入成功与否
pair<map<int, string>::iterator,bool> pair1=map1.insert(make_pair(0, "stu1"));
if (pair1.second == true)
{
cout << "插入成功" << endl;
cout << pair1.first->first << " " << pair1.first->second << endl;
}
else
{
cout << "插入失败" << endl;
}
printFun(map1);
pair<map<int, string>::iterator, bool> pair2 = map1.insert(make_pair(7, "stu1"));
if (pair2.second == true)
{
cout << "插入成功" << endl;
cout << pair2.first->first << " " << pair2.first->second << endl;
}
else
{
cout << "插入失败" << endl;
}
printFun(map1);
//查找
map<int, string>::iterator it1=map1.find(0);
if (it1 != map1.end()) cout << it1->first << " " << it1->second << endl;
else cout << "元素不存在" << endl;
it1 = map1.lower_bound(1);//大于等于1
if (it1 != map1.end()) cout << it1->first << " " << it1->second << endl;
else cout << "元素不存在" << endl;
it1 = map1.upper_bound(1);//大于1
if (it1 != map1.end()) cout << it1->first << " " << it1->second << endl;
else cout << "元素不存在" << endl;
pair<map<int, string>::iterator, map<int, string>::iterator> pair3;
pair3 = map1.equal_range(1);//大于和等于1
if (pair3.first==map1.end())
{
cout << "第一个迭代器不存在" << endl;
}
else
{
cout << pair3.first->first << " " << pair3.first->second << endl;
}
if (pair3.second == map1.end())
{
cout << "第二个迭代器不存在" << endl;
}
else
{
cout << pair3.second->first << " " << pair3.second->second << endl;
}
system("pause");
return 0;
}
multimap 相比map key允许重复
#include<map>
#include<string>
#include<iostream>
using namespace std;
class Person
{
public:
Person(int age, string name)
{
this->age = age;
this->name = name;
}
int age;
string name;
};
void printFun(multimap<string, Person>&obj)
{
for (multimap<string, Person>::iterator it = obj.begin(); it != obj.end(); it++)
{
cout << it->first << "\t" << it->second.age << "\t" << it->second.name << endl;
}
}
int main()
{
multimap<string, Person> mulmap;
Person p1(20, "A");
Person p2(40, "B");
Person p3(10, "C");
Person p4(20, "D");
Person p5(35, "E");
Person p6(25, "F");
mulmap.insert(make_pair("sale", p1));
mulmap.insert(make_pair("sale", p2));
mulmap.insert(make_pair("develop", p3));
mulmap.insert(make_pair("sale", p4));
mulmap.insert(make_pair("develop", p5));
mulmap.insert(make_pair("develop", p6));
printFun(mulmap);
system("pause");
return 0;
}