C++でマップコレクションを繰り返し処理する方法は何ですか。
C++で、std::mapコレクションを反復処理するために、イテレータを使用することができます。以下にstd::mapを反復処理するためのサンプルコードがあります:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
// 向map中插入元素
myMap.insert(std::make_pair(1, "apple"));
myMap.insert(std::make_pair(2, "banana"));
myMap.insert(std::make_pair(3, "orange"));
// 使用迭代器遍历map
std::map<int, std::string>::iterator itr;
for(itr = myMap.begin(); itr != myMap.end(); ++itr) {
std::cout << "Key: " << itr->first << ", Value: " << itr->second << std::endl;
}
return 0;
}
上記のコードは、std::mapオブジェクトであるmyMapを作成し、3つのキーバリューペアを挿入しています。そして、イテレーターitrを使用してmyMapを走査し、各キーバリューペアのキーと値を出力しています。
結果は出力されました。
Key: 1, Value: apple
Key: 2, Value: banana
Key: 3, Value: orange
std::mapはキーの自然な順序でソートされた順序付きです。集合を挿入した順序で走査したい場合は、std::mapの代わりにstd::unordered_mapを使用できます。