c++如何遍历anordered_map容器
可以通过迭代器来遍历unordered_map容器。具体方法如下:
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<int, string> myMap = {{1, "apple"}, {2, "banana"}, {3, "orange"}};
//遍历unordered_map容器
for (auto it = myMap.begin(); it != myMap.end(); ++it)
{
cout << it->first << ":" << it->second << endl;
}
return 0;
}
输出结果:
1:apple
2:banana
3:orange
其中,auto关键字可以自动推断迭代器类型,it->first表示键,it->second表示值。
原文地址: http://www.cveoy.top/t/topic/bnaR 著作权归作者所有。请勿转载和采集!