迭代器是C++ STL中遍历容器的核心工具,提供统一访问方式。1. 基本类型包括iterator(读写)、const_iterator(只读)、reverse_iterator(反向)和const_reverse_iterator(反向只读)。2. 使用begin()指向首元素,end()指向末尾后位置,通过循环遍历容器。3. 用cbegin()和cend()获取const_iterator,避免意外修改。4. rbegin()和rend()实现反向遍历,从尾到头访问元素。5. C++11推荐范围for循环(for (const auto& value : container)),语法简洁且安全。6. 所有标准容器(如vector、map等)均支持迭代器遍历,结合auto可提升代码效率与可读性。

在C++ STL中,迭代器是遍历容器元素的核心工具。它类似于指针,指向容器中的某个元素,通过递增或递减操作访问下一个或上一个元素。使用迭代器可以统一不同容器的访问方式,提高代码的通用性和可维护性。
STL提供了多种迭代器类型,适用于不同的容器和操作需求:
每个STL容器都提供 begin() 和 end() 成员函数:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
for (auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " ";
}
// 输出: 1 2 3 4 5
return 0;
}
当不需要修改容器内容时,推荐使用 const_iterator 提高安全性:
立即学习“C++免费学习笔记(深入)”;
for (auto it = vec.cbegin(); it != vec.cend(); ++it) {
std::cout << *it << " ";
}
注意使用 cbegin() 和 cend() 获取 const 迭代器。
使用 rbegin() 和 rend() 实现逆序访问:
for (auto rit = vec.rbegin(); rit != vec.rend(); ++rit) {
std::cout << *rit << " ";
}
// 输出: 5 4 3 2 1
现代C++推荐使用基于范围的for循环,更简洁安全:
for (const auto& value : vec) {
std::cout << value << " ";
}
底层仍使用迭代器,但语法更清晰,避免了手动管理迭代器边界。
以下方法适用于所有标准容器(vector、list、set、map等):
std::map<std::string, int> m = {{"a", 1}, {"b", 2}};
for (auto it = m.begin(); it != m.end(); ++it) {
std::cout << it->first << ": " << it->second << " ";
}
以上就是c++++怎么使用迭代器遍历容器_c++ STL迭代器遍历容器方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号