加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c++STL容器之map容器

发布时间:2020-12-16 09:06:39 所属栏目:百科 来源:网络整理
导读:1.map中所有的元素都是pair; 2.pair元素中第一个元素为key,第二个元素为value; 3.所有元素都会根据键值自动排序; 4.map中不允许有重复的键,multimap中允许有重复的键; 优点:可以根据key快速的找到value; 一、构造函数 mapT1,T2 mp;map( const map mp

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修饰。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读