📅  最后修改于: 2023-12-03 15:30:06.664000             🧑  作者: Mango
Map 是 C++ STL 中的一种关联式容器,可以将一个键映射到一个值上,类似于字典。Map 中的键必须是唯一的,而值可以重复。因此,我们有时需要遍历 Map 中的键。本文将介绍 C++ Map 遍历键的几种方法。
使用 for 循环和迭代器来遍历 Map 中的键:
#include <iostream>
#include <map>
int main()
{
std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << std::endl;
}
return 0;
}
上述代码中,我们遍历了 Map 中的每一个元素,通过访问迭代器的 first
成员可以获得每个键的值。
使用 range-based for 循环来遍历 Map 中的键:
#include <iostream>
#include <map>
int main()
{
std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
for (auto const& [key, value] : myMap) {
std::cout << key << std::endl;
}
return 0;
}
这种方法使用了 C++17 的结构化绑定特性,通过 key
变量即可获取每个键的值。
使用 for_each 算法和 Lambda 表达式来遍历 Map 中的键:
#include <iostream>
#include <map>
#include <algorithm>
int main()
{
std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}};
std::for_each(myMap.begin(), myMap.end(), [](auto const& element) {
std::cout << element.first << std::endl;
});
return 0;
}
上述代码中,我们使用了 for_each
算法来遍历每个元素,通过 Lambda 表达式访问 first
成员可以获得每个键的值。
以上就是 C++ Map 遍历键的几种方法。具体使用哪种方法取决于个人习惯和情境。