C++ map iterator遍历有哪些技巧

   2024-10-02 3480
核心提示:在C++中,可以使用迭代器遍历std::map容器。以下是一些技巧:使用auto关键字自动推导迭代器类型:std::mapint, std::string myMa

在C++中,可以使用迭代器遍历std::map容器。以下是一些技巧:

使用auto关键字自动推导迭代器类型:
std::map<int, std::string> myMap;// 使用auto关键字自动推导迭代器类型for (auto it = myMap.begin(); it != myMap.end(); ++it) {    // 迭代器操作}
使用范围for循环:
std::map<int, std::string> myMap;// 使用范围for循环for (const auto& pair : myMap) {    // pair为键值对,first为键,second为值}
使用迭代器的成员函数:
std::map<int, std::string> myMap;// 使用迭代器的成员函数for (auto it = myMap.begin(); it != myMap.end(); ++it) {    std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;}
使用find函数查找特定键值对:
std::map<int, std::string> myMap;int keyToFind = 1;auto it = myMap.find(keyToFind);if (it != myMap.end()) {    // 找到了特定键值对    std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;} else {    // 未找到特定键值对    std::cout << "Key not found" << std::endl;}

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号