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

原文链接: https://www.cnblogs.com/cff2121/p/11653937.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++中map的用法

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/303975

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 上午1:22
下一篇 2023年2月16日 上午1:24

相关推荐