ที่นี่เราจะมาดูวิธีใช้ช่วงตามลูปสำหรับวัตถุประเภทแผนที่ std::map ใน C ++ เรารู้ว่ามีวัตถุประเภทแผนที่ ที่สามารถเก็บคู่ค่าคีย์ แผนที่โดยทั่วไปจะจัดเก็บวัตถุคู่ ออบเจ็กต์คู่นี้ใช้เพื่อเก็บหนึ่งคีย์และค่าที่สอดคล้องกัน คีย์และค่าเหล่านี้ใช้งานโดยใช้เทมเพลต เราจึงใช้ข้อมูลประเภทใดก็ได้
ในการใช้ช่วงที่อิงจากลูป เราสามารถกำหนด for loop ที่สามารถวนซ้ำผ่านแต่ละคู่ของแผนที่ได้ มาดูโค้ดกันเลยดีกว่าครับ
โค้ดตัวอย่าง
#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