c++

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

小樊
101
2024-07-30 11:24:12
栏目: 编程语言

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

  1. 使用auto关键字自动推导迭代器类型:
std::map<int, std::string> myMap;
// 使用auto关键字自动推导迭代器类型
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
    // 迭代器操作
}
  1. 使用范围for循环:
std::map<int, std::string> myMap;
// 使用范围for循环
for (const auto& pair : myMap) {
    // pair为键值对,first为键,second为值
}
  1. 使用迭代器的成员函数:
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;
}
  1. 使用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;
}

0
看了该问题的人还看了