c++STL容器之map容器

c++STL容器之map容器,第1张

概述1.map中所有的元素都是pair; 2.pair元素中第一个元素为key,第二个元素为value; 3.所有元素都会根据键值自动排序; 4.map中不允许有重复的键,multimap中允许有重复的键

1.map中所有的元素都是pair;

2.pair元素中第一个元素为key,第二个元素为value;

3.所有元素都会根据键值自动排序;

4.map中不允许有重复的键,multimap中允许有重复的键;

优点:可以根据key快速的找到value;

一、构造函数

map<T1,T2> mp;map(const map &mp);

二、赋值

map& operator=(三、map大小和交换

size();empty();swap(st);

四、插入和删除

insert(ele);clear();erase(pos);erase(beg,end);erase(key);
#include<iostream>using namespace std;#include <map>//map容器 插入和删除voID printMap(map<int,int>&m){    for (map<int>::iterator it = m.begin(); it != m.end(); it++)    {        cout << "key = " << it->first <<  value = " << it->second << endl;    }    cout << endl;}voID test01(){    map<int>m;    插入    第一种    m.insert(pair<int>(1,10));    第二种    m.insert(make_pair(2,1)">20第三种    m.insert(map<int>::value_type(3,1)">30第四种    m[4] = 40;    []不建议插入,用途 可以利用key访问到value    cout << m[4] << endl;    printMap(m);    删除    m.erase(m.begin());    printMap(m);    m.erase(3); 按照key删除    printMap(m);    清空    m.erase(m.begin(),m.end());    m.clear();    printMap(m);}int main() {    test01();    system(pause");    return 0;}

五、查找和统计

 test01(){    查找    map<m;    m.insert(pair<));    m.insert(pair<));    map<int>::iterator pos = m.find(3if (pos != m.end())    {        cout << 查到了元素 key = " << (*pos).first << " << pos->second << endl;    }    else    {        cout << 未找到元素" << endl;    }    统计    map不允许插入重复key 元素 ,count统计而言 结果要么是0 要么是1    multimap的count统计可能大于1    int num = m.count();    cout << num = " << num << endl;}

六、map排序(按升序排序)

#include<iostream>class MyCompare{public:    bool operator()(int v1,1)">int v2) const    {        降序        return v1 > v2;    }};map容器 排序m;    m.insert(make_pair());    m.insert(make_pair(5,1)">504,1)">));     endl;    }};}

vs2019在重载operator()时需要用const修饰。

总结

以上是内存溢出为你收集整理的c++STL容器之map容器 全部内容,希望文章能够帮你解决c++STL容器之map容器 所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1159559.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-01
下一篇 2022-06-01

发表评论

登录后才能评论

评论列表(0条)

保存