在这里,我们将看到如何为std::map类型的对象使用基于范围的for循环。在C ++中,我们知道有映射类型的对象。那可以存储键值对。该映射基本上存储了配对对象。该对对象用于存储一个键和相应的值。这些键和值是使用模板实现的,因此我们可以使用任何类型的数据。
要使用基于范围的for循环,我们可以定义for循环,该循环可以遍历映射的每一对。让我们看一下代码以获得更好的主意。
#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