21xrx.com
2024-09-20 00:00:23 Friday
登录
文章检索 我的文章 写文章
「C++」Map 的多种遍历方式
2023-07-03 10:09:35 深夜i     --     --
C++ Map 遍历 多种 方式

在C++中,Map是一种非常方便的数据结构。它提供了键值对映射的功能,可以很快地查找对应的值。但是,在实际应用中,我们不仅需要查找,还需要对Map进行遍历。那么,C++中Map有哪些多种遍历方式呢?

1. 迭代器遍历

使用迭代器遍历Map是最基本的方法,也是最常用的方法。通过遍历Map中的迭代器,可以访问Map中的每个数据。可以使用以下代码实现:


#include <iostream>

#include <map>

using namespace std;

int main() {

  map<int, string> myMap;

  myMap.insert(pair<int, string>(1, "hello"));

  myMap.insert(pair<int, string>(2, "world"));

  myMap.insert(pair<int, string>(3, "C++"));

  for (auto it = myMap.begin(); it != myMap.end(); it++)

    cout << it->first << " " << it->second << endl;

  

  return 0;

}

2. C++11的auto关键字遍历

C++11中新增了auto关键字,可以自动推导数据类型。在Map中,使用auto可以非常方便地遍历Map中的数据。可以使用以下代码实现:


#include <iostream>

#include <map>

using namespace std;

int main() {

  map<int, string> myMap = {1, 2, {3, "C++"}};

  for (auto& [key, value] : myMap)

    cout << key << " " << value << endl;

  

  return 0;

}

3. 逆序遍历

有时我们需要逆序遍历Map,C++中提供了rbegin()和rend()方法,可以实现逆序遍历。可以使用以下代码实现:


#include <iostream>

#include <map>

using namespace std;

int main() {

  map<int, string> myMap = { "hello", 2, {3, "C++"}};

  for (auto it = myMap.rbegin(); it != myMap.rend(); it++)

    cout << it->first << " " << it->second << endl;

  

  return 0;

}

总结

以上就是C++中Map的多种遍历方式,其中第二种方法是C++11新增的,能够非常便利地遍历Map中的数据,而第三种方法可以实现逆序遍历。对于不同的需求,可以选择不同的遍历方式。如有数据内容众多,那么使用迭代器遍历可能会非常耗时。而使用auto关键字和逆序遍历,则可能会更加高效。通过选择最合适的遍历方式,可以使代码更加简洁高效,提高程序运行效率。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复