C++ std::map几种遍历方式(正序、倒序)
文章目录
1、map 的定义方式
//默认定义格式(默认按key升序存储): key, value,其中key可以是任意类型
std::map<std::uint32_t, std::string> myMap; //key 值为 std::uint32_t 类型
std::map<std::string, std::string> myMap; //key 值为 std::string 类型
//指定数据按key升序存储
std::map<std::uint32_t, std::string, std::greater<std::uint32_t> > myMap;
//指定数据按key升序存储
std::map<std::uint32_t, std::string, std::less<std::uint32_t> > myMap;
2、正序遍历 map
注意:正序使用的是 std::map<std::uint32_t, std::string>::iterator, 倒序使用的是:std::map<std::uint32_t, std::string>::reverse_iterator。
2.1 使用 for 循环
#include <iostream>
#include <map>
int main()
{
std::map<std::uint32_t, std::string> myMap = {
{
1, "one"}, {
2, "two"}, {
3, "three"}};
// 使用迭代器倒序遍历map
std::map<std::uint32_t, std::string>::iterator iter;
for (iter = myMap.begin(); iter != myMap

本文主要介绍C++中std::map的几种遍历方式,包括正序和倒序遍历。先说明了map的定义方式,接着分别阐述正序和倒序遍历中使用for循环和while循环的方法,还提及使用std::greater属性直接定义倒序存储的map及其遍历方式。
最低0.47元/天 解锁文章
3万+

被折叠的 条评论
为什么被折叠?



