C++のイテレータでマップを反復処理する方法

マップを反復処理するための C++ イテレータの使用方法を次に示します。

  1. mapの最初のイテレータを取得するには、begin()関数を使いましょう。
  2. mapの最後のイテレータをend()関数で取得します。
  3. Map 要素を反復処理できるまで、for 反復処理や while 反復処理などの反復処理構造と反復処理を使用して Map 内の要素を順番に走査します。
  4. map内のキーと値には、反復子のfirstメンバとsecondメンバを使ってアクセスする。

サンプルコードを以下に示します。

#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "One";
myMap[2] = "Two";
myMap[3] = "Three";
// 使用迭代器遍历map
std::map<int, std::string>::iterator it;
for (it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << " Value: " << it->second << std::endl;
}
return 0;
}

実行結果:

Key: 1 Value: One
Key: 2 Value: Two
Key: 3 Value: Three
bannerAds