C++如何使用迭代器_C++ STL容器遍历器(Iterator)的基本用法

迭代器是C++ STL中用于统一访问容器元素的对象,支持begin()和end()遍历,可应用于vector、list、map等容器,结合auto和范围for循环提升代码安全与简洁性。

在C++中,迭代器(Iterator)是STL(标准模板库)中用于遍历容器元素的重要工具。它类似于指针,可以指向容器中的某个元素,并通过递增或递减来访问其他元素。使用迭代器可以统一不同容器的访问方式,提高代码的通用性和可维护性。

什么是迭代器

迭代器是一种对象,它允许程序员以相同的方式访问不同类型的STL容器(如 vector、list、set、map 等),而无需关心容器内部的具体实现。每个支持迭代器的容器都提供了以下两个关键成员函数:

  • begin():返回指向容器第一个元素的迭代器
  • end():返回指向容器“末尾之后”位置的迭代器(不指向有效元素)

通过从 begin() 到 end() 的遍历,可以访问容器中的所有元素。

常见容器的迭代器用法

下面展示几种常用STL容器中迭代器的基本使用方式。

1. 使用 vector 的迭代器

vector 是动态数组,支持随机访问迭代器。

#include 
#include 
using namespace std;

int main() {
    vector nums = {1, 2, 3, 4, 5};

    // 使用迭代器遍历
    for (auto it = nums.begin(); it != nums.end(); ++it) {
        cout << *it << " ";
    }
    cout << endl;

    return 0;
}

2. 使用 list 的迭代器

list 是双向链表,也支持双向迭代器。

#include 
#include 
using namespace std;

int main() {
    list words = {"hello", "world", "STL"};

    for (auto it = words.begin(); it != words.end(); ++it) {
        cout << *it << " ";
    }
    cout << endl;

    return 0;
}

3. 使用 map 的迭代器

map 是关联容器,存储键值对,迭代器指向 pair 类型元素。

#include 
#include 
using namespace std;

int main() {
    map ages;
    ages["Alice"] = 25;
    ages["Bob"] = 30;

    for (auto it = ages.begin(); it != ages.end(); ++it) {
        cout << it->first << ": " << it->second << endl;
    }

    return 0;
}

const_iterator 与 auto 关键字

如果只是读取容器内容而不修改,建议使用 const_iterator 或 const auto& 来保证安全性。

  • const_iterator:只能读取元素,不能修改
  • auto:让编译器自动推导迭代器类型,减少书写错误

现代C++推荐写法:

// 推荐方式:简洁且安全
for (const auto& elem : container) {
    cout << elem << " ";
}

// 或使用 auto it 遍历
for (auto it = container.begin(); it != container.end(); ++it) {
    // ...
}

反向迭代器(reverse_iterator)

STL还提供反向迭代器,用于从后往前遍历。

  • rbegin():指向最后一个元素
  • rend():指向第一个元素前一个位置

示例:

vector nums = {1, 2, 3, 4, 5};
for (auto rit = nums.rbegin(); rit != nums.rend(); ++rit) {
    cout << *rit << " ";
}
// 输出:5 4 3 2 1

基本上就这些。掌握 begin/end、auto 推导和范围 for 循环,就能高效使用C++迭代器。注意不要对 end() 迭代器解引用,也不要在遍历时随意插入/删除元素(除非使用支持的安全方法)。