对map进行遍历
对map进行遍历可以使用迭代器或者range循环来实现。以下是两种常用的遍历方式:
- 使用迭代器遍历map:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "apple";
myMap[2] = "banana";
myMap[3] = "orange";
// 使用迭代器遍历map
std::map<int, std::string>::iterator it;
for (it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << " : " << it->second << std::endl;
}
return 0;
}
- 使用range循环遍历map(C++11及以上版本支持):
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "apple";
myMap[2] = "banana";
myMap[3] = "orange";
// 使用range循环遍历map
for (const auto& pair : myMap) {
std::cout << pair.first << " : " << pair.second << std::endl;
}
return 0;
}
以上两种方式都可以实现对map的遍历,根据实际需求选择合适的方法即可
原文地址: https://www.cveoy.top/t/topic/hJsA 著作权归作者所有。请勿转载和采集!