zoukankan      html  css  js  c++  java
  • C++中map的用法

    头文件

    使用map应包含map头文件

    #include<map>

    map的定义和初始化

    定义:

    map<int,int> m;

    尖括号内第一个数据类型表示键的类型,第二个为值的数据类型

    初始化:

    方法一:直接指定键,并赋值

    例1:

    map<int, int> m;
    m[1] = 1000;
    map<int, int>::iterator it = m.begin();
    cout << "key:" << it->first << endl;
    cout << "value is:" << it->second << endl;

    结果为:

    key:1
    value is:1000

    方法二:插入键值对

    例2:

    map<int, int> m;
    m.insert(make_pair(1, 999));
    map<int, int>::iterator it = m.begin();
    cout << "key:" << it->first << endl;
    cout << "value is:" << it->second << endl;

    结果为:

    key:1
    value is:999

    map遍历:

    使用迭代器遍历

    例3:

    map<int, string> m;
    for (int i = 0; i < 10; ++i) {
        stringstream ss;
        char c = 'a' + i;
        ss << c;
        m[i + 1] = ss.str();
    }
    map<int, string>::iterator it = m.begin();  //定义并初始化m相应的迭代器,并赋值为m的开端指针。
    while (it != m.end()) {
        cout << "key:" << it->first << ",value is:" << it->second << endl;  //map类型的迭代器的first是map的键,second是值。
        it++;
    }

    结果为:

    key:1,value is:a
    key:2,value is:b
    key:3,value is:c
    key:4,value is:d
    key:5,value is:e
    key:6,value is:f
    key:7,value is:g
    key:8,value is:h
    key:9,value is:i
    key:10,value is:j

    map删除元素

    1.erase()函数

    例4:

    参数为迭代器:

    m.erase(m.begin());

    参数为某个键:

    m.erase(1);

    都可进行删除,m的内容同例3

    输出结果为:

    key:2,value is:b
    key:3,value is:c
    key:4,value is:d
    key:5,value is:e
    key:6,value is:f
    key:7,value is:g
    key:8,value is:h
    key:9,value is:i
    key:10,value is:j

    2.clear()函数,用于清空map

    map查找:

    1.直接使用键从map中找到对应的值

     例6:

    cout << m[3] << endl;

    结果为:c

    2.使用find()函数找到指定元素

    例7:

    map<int, string>::iterator it = m.find(3);
    cout << "key:" << it->first << ",value is:" << it->second << endl;

    结果为:key:3,value is:c

    判断map是否为空:

    map.empty()

    计算map的大小:

    map.size()

    无序map:unordered_map

  • 相关阅读:
    左孩子右兄弟的字典树
    UVA 1401 Remember the Word
    HDOJ 4770 Lights Against Dudely
    UvaLA 3938 "Ray, Pass me the dishes!"
    UVA
    Codeforces 215A A.Sereja and Coat Rack
    Codeforces 215B B.Sereja and Suffixes
    HDU 4788 Hard Disk Drive
    HDU 2095 find your present (2)
    图的连通性问题—学习笔记
  • 原文地址:https://www.cnblogs.com/cff2121/p/11653937.html
Copyright © 2011-2022 走看看