如何使用基於範圍的 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

更新時間:30-07-2019

2 千次瀏覽

開啟您的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.