📜  C++中的双向迭代器(1)

📅  最后修改于: 2023-12-03 15:14:03.443000             🧑  作者: Mango

C++ 中的双向迭代器

迭代器是一种对象,它可以用于遍历 STL 容器中的元素。类似于指针,迭代器可以指向容器的元素,它们提供了访问容器底层数据结构中的元素的方法。

在 C++ 中,迭代器分为五类,分别是:输入迭代器、输出迭代器、前向迭代器、双向迭代器和随机访问迭代器。本文将着重介绍其中的双向迭代器。

双向迭代器

双向迭代器是一种迭代器,它可以从前向后遍历容器中的元素,也可以从后向前遍历容器中的元素。在 STL 中,双向迭代器可以用于访问和修改顺序容器中的元素,例如链表、双向链表、队列和堆栈等。

C++ 标准库中的标准容器 std::deque,std::list 和 std::set 等都提供了双向迭代器。下面我们以 std::list 为例,介绍双向迭代器的用法。

创建双向迭代器

使用 C++ 的标准库,创建一个双向迭代器很容易,只需要使用 std::list 的成员函数 begin() 和 end() 即可。其中 begin() 函数返回指向链表头部节点的迭代器,end() 函数返回指向链表尾部节点后的迭代器。

#include <iostream>
#include <list>

using namespace std;

int main() {
    list<int> my_list{1, 2, 3, 4, 5};
    list<int>::iterator itr_begin = my_list.begin();
    list<int>::iterator itr_end = my_list.end();
    return 0;
}

在上面的例子中,我们创建了一个 std::list,并使用 begin() 和 end() 函数创建了两个双向迭代器。其中 itr_begin 迭代器指向链表头部节点,itr_end 迭代器指向链表尾部节点后的位置。

遍历双向迭代器

遍历双向迭代器相当于遍历容器中的元素。我们可以使用迭代器的自增和自减运算符来实现遍历。对于双向迭代器,我们可以使用 ++ 运算符实现从前向后遍历,使用 -- 运算符实现从后向前遍历。

#include <iostream>
#include <list>

using namespace std;

int main() {
    list<int> my_list{1, 2, 3, 4, 5};
    list<int>::iterator itr_begin = my_list.begin();
    list<int>::iterator itr_end = my_list.end();
    
    cout << "遍历输出 my_list 中的元素:" << endl;
    while (itr_begin != itr_end) {
        cout << *itr_begin << " ";
        ++itr_begin;
    }
    cout << endl;
    
    cout << "倒序遍历输出 my_list 中的元素:" << endl;
    --itr_end;
    while (itr_end != my_list.begin()) {
        cout << *itr_end << " ";
        --itr_end;
    }
    cout << *itr_end << endl;
    
    return 0;
}

在上面的例子中,我们使用了 ++ 和 -- 运算符遍历了双向迭代器,输出了容器中的元素。值得注意的是,在倒序遍历时,要先将迭代器指向尾部节点的位置,然后再进行遍历。因为使用 -- 运算符遍历时,迭代器不能超出容器的范围,否则会发生未定义行为。

修改双向迭代器指向的元素

与遍历容器中的元素类似,双向迭代器也可以用来修改容器中的元素。和指针一样,我们可以使用迭代器访问元素并修改其值。例如:

#include <iostream>
#include <list>

using namespace std;

int main() {
    list<int> my_list{1, 2, 3, 4, 5};
    list<int>::iterator itr_begin = my_list.begin();
    list<int>::iterator itr_end = my_list.end();
    
    cout << "修改前 my_list 中的元素:" << endl;
    while (itr_begin != itr_end) {
        cout << *itr_begin << " ";
        ++itr_begin;
    }
    cout << endl;
    
    itr_begin = my_list.begin();  // 再次初始化迭代器,从头部开始遍历
    while (itr_begin != itr_end) {
        *itr_begin = *itr_begin + 1;  // 将指向的元素值加1
        ++itr_begin;
    }
    
    itr_begin = my_list.begin();  // 再次初始化迭代器,从头部开始遍历
    cout << "修改后 my_list 中的元素:" << endl;
    while (itr_begin != itr_end) {
        cout << *itr_begin << " ";
        ++itr_begin;
    }
    cout << endl;
    
    return 0;
}

在上面的例子中,我们遍历了 std::list 的所有元素,并将元素的值都加了 1。最终将修改后的元素输出,用来验证修改操作的正确性。

总结

双向迭代器是一种方便灵活的迭代器,它能够从前向后遍历容器中的元素,也可以从后向前遍历容器中的元素。在 C++ 的标准库中,许多常用容器,如 std::list 和 std::set 等都提供了双向迭代器,方便开发者对容器中的元素进行访问和操作。