如何使用基于范围的 for() 循环使用 std::map?
本文将介绍如何在 std::map 类型对象中使用基于范围的 for 循环。在 C++ 中,我们知道有 map 类型对象。它可以存储键值对。map 基本上存储配对对象。该配对对象用于存储一个键和一个对应的值。这些键和值使用模板实现,因此我们可以使用任何类型的数据。
要使用基于范围的 for 循环,我们可以定义一个 for 循环,该循环可以迭代 map 的每个配对。我们来看一下代码以获得更好的理解。
示例代码
#include<iostream>
#include<map>
using namespace std;
main() {
map<char, string> my_map;
my_map.insert(pair<char, string>('A', "Apple"));
my_map.insert(pair<char, string>('B', "Ball"));
my_map.insert(pair<char, string>('C', "Cat"));
my_map.insert(pair<char, string>('D', "Dog"));
my_map.insert(pair<char, string>('E', "Eagle"));
my_map.insert(pair<char, string>('F', "Flag"));
my_map.insert(pair<char, string>('G', "Ghost"));
my_map.insert(pair<char, string>('H', "Hill"));
my_map.insert(pair<char, string>('I', "India"));
my_map.insert(pair<char, string>('J', "Jug"));
for(auto& key_val : my_map) {
cout << "The " << key_val.first << " is pointing to: " << key_val.second << endl;
}
}输出
The A is pointing to: Apple The B is pointing to: Ball The C is pointing to: Cat The D is pointing to: Dog The E is pointing to: Eagle The F is pointing to: Flag The G is pointing to: Ghost The H is pointing to: Hill The I is pointing to: India The J is pointing to: Jug
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP