ที่นี่เราจะดูวิธีใช้ range-based for loop สำหรับ std::map ใน C++ map เก็บ key-value pairs โดยเก็บเป็น pair objects pair ใช้ templates จึงใช้ข้อมูลชนิดใดก็ได้
เพื่อใช้ range-based for loop กำหนด for loop วนผ่านแต่ละ pair ของ map มาดูโค้ด
ตัวอย่างโค้ด
#include <iostream>
#include <map>
using namespace std;
int 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