map简介:
1.map中所有元素都是pair
2.pair中第一个元素为key(键值),起索引作用,第二个元素为value(实值)
3.所有元素都会根据元素的键值自动排序
优点:
可以根据key的值快速找到value值
map/multimap区别:
map不允许有重复值,multimap允许
//map构造函数用法:
#include <iostream>
#include<string>
#include<map>
class Person {
public:
Person(string name, int age) {
this->m_Name = name;
this->m_Age = age;
}
string m_Name;
int m_Age;
};
class comparePerson {
public:
bool operator()(const Person&p1, const Person &p2) {
return p1.m_Age > p2.m_Age;
}
};
void printMap(map<int,int>&m) {
for (map <int,int>::iterator it = m.begin(); it != m.end(); it++) {
cout << "key="<< (*it).first<<"value="<<(*it).second<<endl;
}
cout << endl;
}
void test01() {
map<int, int>m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(3, 20));
m.insert(pair<int, int>(2, 30));
m.insert(pair<int, int>(4, 40));
printMap(m);
}
int main()
{
test01();
system("pause");
return 0;
}