C++中遍历std::map主要有三种方式:基于范围的for循环(C++11)简洁易读,适合只读场景;显式迭代器循环灵活安全,支持遍历时删除元素;结构化绑定(C++17)进一步提升可读性,直接解构键值对。选择依据包括是否需修改容器、代码风格及C++标准支持。

C++中遍历
std::map
遍历
std::map
解决方案
首先,要理解
std::map
std::pair<const Key, Value>
立即学习“C++免费学习笔记(深入)”;
基于范围的for循环 (C++11及更高版本) 这是最现代、最简洁的遍历方式,对于只需要读取
map
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<int, std::string> myMap = {
{1, "Apple"},
{2, "Banana"},
{3, "Cherry"}
};
// 遍历并打印键值对
for (const auto& pair : myMap) { // 使用const auto& 避免不必要的拷贝,并确保不会意外修改键或值
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
// 如果需要修改值(但不修改键,因为map的键是const的),可以使用 auto&
for (auto& pair : myMap) {
if (pair.first == 2) {
pair.second = "Blueberry"; // 可以修改值
}
}
std::cout << "\nAfter modification:" << std::endl;
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
return 0;
}这种方式的优点显而易见:代码量少,可读性高。但它不适合在遍历过程中删除元素,因为直接删除会导致迭代器失效,引发未定义行为。
显式迭代器循环 (传统方式) 这是最基础、最灵活的遍历方法,在C++98时代就广泛使用,至今仍是处理复杂迭代逻辑(如在遍历时删除元素)的首选。
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<int, std::string> myMap = {
{1, "Apple"},
{2, "Banana"},
{3, "Cherry"},
{4, "Date"}
};
// 传统迭代器遍历
for (std::map<int, std::string>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
// 示例:在遍历时删除元素 (这是迭代器循环的优势所在)
std::cout << "\nDeleting elements with even keys:" << std::endl;
for (auto it = myMap.begin(); it != myMap.end(); ) { // 注意这里没有++it
if (it->first % 2 == 0) {
std::cout << "Deleting Key: " << it->first << std::endl;
it = myMap.erase(it); // erase() 返回下一个有效迭代器,这是关键!
} else {
++it; // 只有在不删除元素时才手动递增
}
}
std::cout << "\nMap after deletion:" << std::endl;
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
return 0;
}显式迭代器提供了对迭代过程的完全控制,尤其是在涉及到容器修改时,其灵活性是其他方法无法比拟的。
结构化绑定 (C++17及更高版本) 这是基于范围的for循环的进一步语法糖,它允许你直接将
std::pair
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<int, std::string> myMap = {
{1, "Apple"},
{2, "Banana"},
{3, "Cherry"}
};
// 使用结构化绑定遍历
for (const auto& [key, value] : myMap) { // 直接解构为key和value
std::cout << "Key: " << key << ", Value: " << value << std::endl;
}
// 同样,如果需要修改值,可以这样
for (auto& [key, value] : myMap) {
if (key == 1) {
value = "Apricot";
}
}
std::cout << "\nAfter modification with structured binding:" << std::endl;
for (const auto& [key, value] : myMap) {
std::cout << "Key: " << key << ", Value: " << value << std::endl;
}
return 0;
}结构化绑定让代码看起来更像是直接操作键和值,而不是一个
pair
C++ map迭代器失效的常见场景与应对策略是什么?
迭代器失效是C++容器操作中一个非常经典且容易出错的问题,尤其是在遍历过程中修改容器。对于
std::map
常见场景:
map::erase(iterator pos)
std::map
map
std::vector
应对策略:
最核心的策略是在删除元素后,正确地获取下一个有效的迭代器。
std::map::erase()
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<int, std::string> myMap = {
{1, "Apple"}, {2, "Banana"}, {3, "Cherry"}, {4, "Date"}, {5, "Elderberry"}
};
std::cout << "Original map:" << std::endl;
for (const auto& [key, value] : myMap) {
std::cout << "Key: " << key << ", Value: " << value << std::endl;
}
std::cout << "\nAttempting to delete elements with even keys safely:" << std::endl;
// 关键点:在for循环中不自动递增迭代器,而是在删除后手动更新
for (auto it = myMap.begin(); it != myMap.end(); ) {
if (it->first % 2 == 0) {
std::cout << " Deleting Key: " << it->first << std::endl;
// erase(it) 返回一个指向下一个元素的迭代器
it = myMap.erase(it);
} else {
// 如果没有删除,才正常递增迭代器
++it;
}
}
std::cout << "\nMap after safe deletion:" << std::endl;
for (const auto& [key, value] : myMap) {
std::cout << "Key: " << key << ", Value: " << value << std::endl;
}
return 0;
}这段代码展示了在循环中安全删除元素的标准做法。记住,
erase
std::map
遍历std::map时,如何选择const迭代器与非const迭代器?
选择
const
const
map
const
const
const_iterator
cbegin()
cend()
何时使用: 当你的目标是只读访问
map
pair.first
pair.second
map
const
const
优点:
const
const
const std::map<K, V> myConstMap;
const
示例:
std::map<int, std::string> myMap = {{1, "One"}, {2, "Two"}};
// 使用cbegin()/cend()获取const迭代器
for (auto it = myMap.cbegin(); it != myMap.cend(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
// it->second = "New Value"; // 编译错误!不能修改const迭代器指向的值
}
// 基于范围的for循环,使用const auto& 也是获取const引用
for (const auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
// pair.second = "New Value"; // 编译错误!
}
// C++17 结构化绑定,同样使用const auto&
for (const auto& [key, value] : myMap) {
std::cout << key << ": " << value << std::endl;
// value = "New Value"; // 编译错误!
}非const
iterator
begin()
end()
何时使用: 当你需要修改
map
const
map
const
优点: 能够修改元素的值。
示例:
std::map<int, std::string> myMap = {{1, "One"}, {2, "Two"}};
// 使用begin()/end()获取非const迭代器
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
if (it->first == 1) {
it->second = "Uno"; // 可以修改值
}
}
// 基于范围的for循环,使用auto&
for (auto& pair : myMap) {
if (pair.first == 2) {
pair.second = "Dos"; // 可以修改值
}
}
// C++17 结构化绑定,同样使用auto&
for (auto& [key, value] : myMap) {
if (key == 1) {
value = "Single"; // 可以修改值
}
}我个人的经验是,总是优先使用
const
const auto&
map
const
除了标准迭代,还有哪些高效或特殊需求的map遍历方式?
除了上面提到的几种基础遍历方式,
std::map
反向遍历 (rbegin()
rend()
map
rbegin()
rend()
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<int, std::string> myMap = {
{10, "Ten"}, {20, "Twenty"}, {30, "Thirty"}, {5, "Five"}
};
std::cout << "Forward traversal:" << std::endl;
for (const auto& [key, value] : myMap) {
std::cout << key << ": " << value << std::endl;
}
std::cout << "\nReverse traversal:" << std::endl;
for (auto it = myMap.rbegin(); it != myMap.rend(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
// 注意:基于范围的for循环不能直接进行反向遍历,需要显式使用rbegin/rend。
// 不过,你可以将map的元素拷贝到vector中再反向遍历vector,但那通常是低效的。
return 0;
}反向遍历在某些场景下非常方便,比如你需要处理最新插入(或最大键)的N个元素时。
基于范围的局部遍历 (lower_bound()
upper_bound()
equal_range()
std::map
map
map
lower_bound(key)
key
upper_bound(key)
key
equal_range(key)
以上就是c++++如何遍历map_c++ map容器遍历技巧与实例的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号