C++におけるunordered_mapのイテレーション方法は何ですか?
C++では、std::unordered_mapをイテレーターで走査することができます。以下は一般的な方法です:
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> myMap = {
{1, "one"},
{2, "two"},
{3, "three"}
};
// 使用迭代器遍历unordered_map
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
return 0;
}
結果を出力します。
Key: 3, Value: three
Key: 2, Value: two
Key: 1, Value: one
上記の例では、myMap.begin()はunordered_mapの最初の要素を指すイテレータを返し、myMap.end()はunordered_mapの末尾要素(最後の要素の次の位置)を指すイテレータを返します。これらのイテレータをforループで使用し、it->firstでキーにアクセスし、it->secondで値にアクセスします。