怀安网站制作,中企动力云邮箱登录,搜索引擎排名优化seo,卖机票的网站怎么做map基本概念
简介#xff1a; map中所有元素都是pair pair中第一个元素为key#xff08;键值#xff09;#xff0c;起到索引作用#xff0c;第二个元素为value#xff08;实值#xff09; 所有元素都会根据元素的键值自动排序
本质#xff1a; map/multimap属于关…map基本概念
简介 map中所有元素都是pair pair中第一个元素为key键值起到索引作用第二个元素为value实值 所有元素都会根据元素的键值自动排序
本质 map/multimap属于关联式容器底层结构是用二叉树实现
优点 可以根据key值快速找到value值
map和multimap区别 map不允许容器中有重复key值元素 multimap允许容器中有重复key值元素
map构造和赋值
功能描述 对map容器进行构造和赋值操作
函数原型 mapT1 T2 mp; //map默认构造函数 map(const map mp); //拷贝构造函数
赋值 map operator(const map mp); //重载等号操作符
map大小和交换
功能描述 统计map容器大小以及交换map容器
函数原型 size(); //返回容器中元素的数目 empty(); //判断容器是否为空 swap(st); //交换两个集合容器
map插入和删除
功能描述 map容器进行插入数据和删除数据
函数原型 insert(elem); // 在容器中插入元素。
//四种插入方法
mapint,intm;
//第一种
m.insert(pairint,int(1,10));
//第二种
m.insert(make_pair(2,20));
//第三种
m.insert(mapint,int::value_type(3,30));
//第四种不建议使用[]插入但可以使用[]访问
//当错误的使用 [] 赋值时会在map中额外的插入一个元素
m[4] 40; clear(); // 清除所有元素 erase(pos); // 删除pos迭代器所指的元素返回下一个元素的迭代器。 erase(beg, end); // 删除区间[beg, end)的所有元素返回下一个元素的迭代器。 erase(key); // 删除容器中值为key的元素。
map查找和统计
功能描述 对map容器进行查找数据以及统计数据
函数原型 find(key); // 查找key是否存在若存在返回该键的元素的迭代器若不存在返回set.end(); count(key); // 统计key的元素个数 查找 --- find 返回的是迭代器 统计 --- count 对于map结果为0或者1
map容器排序 map容器默认排序规则为按照key值进行从小到大排序
主要技术点 利用仿函数可以指定map容器的排序规则 对于自定义数据类型map必须要指定排序规则同set容器
内置数据类型定义仿函数调整map排序方法
#includeiostream
#includestring
#includemap
using namespace std;class myCompare{
public://定义仿函数bool operator()(int a, int b)const{return a b;}
};
int main(){mapint,string m1;m1.insert(pairint,string(10,a));m1.insert(pairint,string(20,b));m1.insert(pairint,string(30,c));m1.insert(pairint,string(40,d));for(mapint,string::iterator it m1.begin(); it ! m1.end(); it){cout it-first it -second endl; }cout -------------------------------- endl;mapint,string,myCompare m2;m2.insert(pairint,string(10,a));m2.insert(pairint,string(20,b));m2.insert(pairint,string(30,c));m2.insert(pairint,string(40,d));for(mapint,string,myCompare::iterator it m2.begin(); it ! m2.end(); it){cout it-first it -second endl; }
} 输出结果如下 自定义数据类型定义仿函数调整map排序方法
如果不定义仿函数则无法直接按键插入自定义数据类型
#includeiostream
#includeset
#includeiostream
#includestring
#includemap
using namespace std;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 Personp1,const Personp2)const{return p1.m_Age p2.m_Age;}
};int main(){Person p1(张三,20);Person p2(李四,21);Person p3(王五,22);Person p4(赵六,23);mapPerson,string,comparePerson m1;m1.insert(pairPerson,string(p1,a));m1.insert(pairPerson,string(p2,b));m1.insert(pairPerson,string(p3,c));m1.insert(pairPerson,string(p4,d));for(mapPerson,string,comparePerson::iterator it m1.begin(); it ! m1.end(); it){cout 姓名 it-first.m_Name 年龄 it-first.m_Age 等级 it -second endl; }}
输出结果如下