Chúng ta sẽ xem cách dùng vòng lặp for dựa trên phạm vi cho đối tượng std::map. Trong C++, map lưu trữ cặp key-value. Map về cơ bản lưu đối tượng pair. Pair này lưu một key và giá trị tương ứng. Key và value dùng template, nên có thể dùng mọi kiểu dữ liệu.
Để dùng range-based for, ta định nghĩa vòng lặp duyệt qua mỗi pair của map. Xem code để hiểu rõ hơn.
Ví dụ Code
#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;
}
}
Kết quả
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