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

  • 相关阅读:
    qml 一个信号与多个方法关联 和 c++信号与槽类似写法
    qml connections使用
    同级qml之间信号与槽
    qml 相互调用 alias 别名
    PBOC规范研究之八----GPO命令(转)
    PBOC规范研究之七 ----应用选择(转)
    PBOC规范研究之六、变长记录文件(转)
    PBOC规范研究之四、文件结构及访问(转)
    C++xml文件操作 CMarkup学习方法说明(转)
    生成tli tlh 文件
  • 原文地址:https://www.cnblogs.com/cff2121/p/11653937.html
Copyright © 2011-2022 走看看