C++ STL 中迭代器概述

原文:https://www.studytonight.com/cpp/stl/stl-iterator-library

正如我们前面讨论的,迭代器用于指向 STL 中的容器,因为迭代器,算法可以操作不同类型的数据结构/容器。

STL 中的算法不在容器上工作,而是在迭代器上工作,它们操作迭代器指向的数据。因此,容器的类型并不重要,正因为如此,算法将适用于任何类型的元素,我们不必为不同类型的容器定义相同的算法。

Overview of Iterators in STL

上图显示了迭代器 ij ,指向一个向量的开始和结束。


在 STL 中定义迭代器

定义迭代器的语法是:

**container_type** <*parameter_list*>::**iterator** *iterator_name*;

让我们看一个更好地理解迭代器的例子:

 #include<iostream>
#include<vector>

using namespace std;

int main()
{
    vector<int>::iterator **i**;
    */* create an iterator named i to a vector of integers */*

    vector<string>::iterator **j**;
    */* create an iterator named j to a vector of strings */*

    list<int>::iterator **k**;
    */* create an iterator named k to a vector of integers */*

    map<int, int>::iterator **l**;
    */* create an iterator named l to a map  of integers */*
}

迭代器可以用来遍历容器,我们可以去引用迭代器来获取它所指向的元素的值。这里有一个例子:

 #include<iostream>
#include<vector>
int main()
{
    vector<int> v(10);
    */* creates an vector v : 0,0,0,0,0,0,0,0,0,0  */*

    vector<int>::iterator i;

    for(i = v.begin(); i! = v.end(); i++)
    cout << *i <<"  ";
    */* in the above for loop iterator I iterates though the 
    vector v and *operator is used of printing the element 
    pointed by it.  */*

return 0;
}