STL-map(ACM)

发布时间 2023-06-11 14:33:55作者: AC玴

1.不存在的元素查询时会自动生成

2.map就是一堆pair的集合,按照T1的字典序进行排列

3.可以像vector那样根据下标随时访问

重载函数

 

map<T1, T2> m; // 下标的类型,值的类型
// 按照T1的值进行字典序排序

// 下方为赋值操作
map<string, string> m;
m["AC"] = "Yee";
m["Red"] = "name";

m.insert(make_pair());
m.insert(x); x是pair类型

 

基本操作

m.insert(make_pair(x, y)) // 不常用,有就无法insert

map<string, int> m;
m.insert(make_pair("AC_Yee's score:", 2600));
for (auto x : m) {
    cout << x.first << x.second << endl;
}
// 输出结果
AC_Yee's score:2600

m.erase() // 删除不存在的地方会RE
m.count();
m.find();
upper_bound();
lower_bound();

map遍历的三种方式

#include <iostream>
#include <unordered_map>
using namespace std;

int main() {
    unordered_map<string, int> mp;
    mp["张三"] = 20;
    mp["李四"] = 18;
    mp["王五"] = 30;

    // 方式一、迭代器
    cout << "方式一、迭代器" << endl;
    for (auto it = mp.begin(); it != mp.end(); it++) {
        cout << it -> first << " " << it -> second << endl;
    }

    // 方式二、range for C++ 11版本及以上
    cout << "\n方法二、 range for" << endl;
    for (auto it : mp) {
        cout << it.first << " " << it.second << endl;
    }

    // 方法三、 C++ 17版本及以上
    cout << "\n方法三" << endl;
    for (auto [key, val] : mp) {
        cout << key  << " " << val << endl;
    }
    
    return 0;
}

自动生成没有的元素

if (m[2] != 0) 
    cout << m[2] << endl;
// 尽管此时m[2]从未赋值过,但使用了就会新建出来m[2]

//当我要判断是否m[2]存在时
if (m.count(2) && m[2] != 0) 
    cout << m[2] << endl;