本质:
优点:
map和multimap区别:
构造:
mapmp;
//默认构造map(const map& mp);
//拷贝构造赋值:
map& operator=(const map& mp);
//重载=运算符map容器所有元素都成对出现,插入数据需要使用对组
#include#include#includeusing namespace std; void PrintMap(const map& mp) { for (map::const_iterator it = mp.begin(); it != mp.end(); it++) { //可以用解引用的方法,也可以用间接访问操作符-> cout << (*it).first << " " << it->second << endl; } cout << endl; } int main() { mapmp; mp.insert(pair(1, 2)); mp.insert(pair(5, 4)); mp.insert(pair(3, 1)); mp.insert(pair(2, 4)); mp.insert(pair(4, 6)); PrintMap(mp); mapmp1; mp1 = mp; PrintMap(mp1); return 0; }
.size();
//返回容器中元素数目.empty();
//判断容器是否为空.swap(mp);
//交换两个集合容器#include#include#includeusing namespace std; void PrintMap(const map& mp) { for (map::const_iterator it = mp.begin(); it != mp.end(); it++) { //可以用解引用的方法,也可以用间接访问操作符-> cout << (*it).first << " " << it->second << endl; } cout << mp.size() << mp.empty() << endl; } int main() { mapmp; mapmp1; mp.insert(pair(1, 2)); mp.insert(pair(5, 4)); mp.insert(pair(3, 1)); mp1.insert(pair(2, 4)); mp1.insert(pair(4, 6)); mp1.insert(pair(6, 6)); PrintMap(mp); PrintMap(mp1); //交换 mp.swap(mp1); //验证交换后的结果 PrintMap(mp); PrintMap(mp1); return 0; }
.insert(elem);
//容器中插入元素pair
方式make_pair
方式value_type
方式[]
下标方式.clear();
//清除所有元素.erase(pos);
//删除pos迭代器所指的元素,返回下一个元素的迭代器.erase(beg,end);
//删除区间[beg,end)内的元素,返回下一个元素的迭代器.erase(key);
//删除容器中值为key的元素#include#include#includeusing namespace std; void PrintMap(const map& mp) { for (map::const_iterator it = mp.begin(); it != mp.end(); it++) { //可以用解引用的方法,也可以用间接访问操作符-> cout << (*it).first << " " << it->second << endl; } cout << endl; } int main() { mapmp; //第一种插入 mp.insert(pair(2, 1)); //第二种插入,不需要写模板参数 mp.insert(make_pair(1, 3)); //第三种,value_type值类型 mp.insert(map::value_type(3, 6)); //第四种,不建议用于插入 mp[4] = 5; //下标方式,如果没有找到,会创建一个实值为0的元素 //作用:可以利用key值访问到value cout << mp[5] << endl; PrintMap(mp); //删除 mp.erase(mp.begin()); mp.erase(5);//按照key删除 PrintMap(mp); return 0; }
.find(key);
//查找key是否存在,返回该键的元素的迭代器,若不存在,返回.end();
.const(key);
//统计key的元素个数,对于map,无非是0或1mapmp; mp.insert(pair(1, 2)); mp.insert(make_pair(2, 2)); mp.insert(map::value_type(3, 1)); if (mp.find(3) != mp.end()) { cout << "找到了" << mp[3] << endl; }
利用仿函数,可以改变排序规则
对于自定义数据类型,map必须指定排序规则,同set容器
#include#include#includeusing namespace std; class myCompare { public: bool operator()(int v1, int v2)const { return v1 > v2; } }; int main() { mapmp; mp.insert(pair(1, 2)); mp.insert(make_pair(2, 2)); mp.insert(map::value_type(3, 1)); for (map::iterator it = mp.begin(); it != mp.end(); it++) { cout << it->first << " " << it->second << endl; } return 0; }
Copyright © 2023 leiyu.cn. All Rights Reserved. 磊宇云计算 版权所有 许可证编号:B1-20233142/B2-20230630 山东磊宇云计算有限公司 鲁ICP备2020045424号
磊宇云计算致力于以最 “绿色节能” 的方式,让每一位上云的客户成为全球绿色节能和降低碳排放的贡献者