迭代器..为什么要使用它们?

2022-01-10 00:00:00 iterator c++ stl

在 STL 库中,一些容器具有迭代器,通常认为它们是遍历这些容器的一种更好的方式,而不是简单的 for 循环,例如

In the STL library some containers have iterators and it is commonly held that they are a superior way of iterating through these containers rather than simple for loops e.g.

for ( int i=0; i < vecVector.size(); i++ )
{

..

}

谁能告诉我为什么以及在什么情况下我应该使用迭代器以及在什么情况下上面的代码片段?

Can anyone tell me why and in what cases I should use iterators and in what cases the code snippet above please?

推荐答案

注意,通常vector的实现不会使用int";作为索引/大小的类型.所以你的代码至少会引发编译器警告.

Note that the usually implementation of vector won't use an "int" as the type of the index/size. So your code will at the very least provoke compiler warnings.

迭代器增加了代码的通用性.

Iterators increase the genericity of your code.

例如:

typedef std::vector<int> Container ;

void doSomething(Container & p_aC)
{
    for(Container::iterator it = p_aC.begin(), itEnd = p_aC.end(); it != itEnd; ++it)
    {
       int & i = *it ; // i is now a reference to the value iterated
       // do something with "i"
    }
}

现在,假设您将向量更改为列表(因为在您的情况下,列表现在更好).只需要修改typedef声明,重新编译代码即可.

Now, let's imagine you change the vector into a list (because in your case, the list is now better). You only need to change the typedef declaration, and recompile the code.

如果您改为使用基于索引的代码,则需要重新编写.

Should you have used index-based code instead, it would have needed to be re-written.

迭代器应该被视为一种超级指针.它点"到值(或者,在映射的情况下,到键/值对).

The iterator should be viewed like a kind of super pointer. It "points" to the value (or, in case of maps, to the pair of key/value).

但它具有移动到容器中下一项的方法.或者上一个.有些容器甚至提供随机访问(向量和双端队列).

But it has methods to move to the next item in the container. Or the previous. Some containers offer even random access (the vector and the deque).

大多数 STL 算法都适用于迭代器或迭代器范围(同样,因为通用性).您将无法在此处使用索引.

Most STL algorithms work on iterators or on ranges of iterators (again, because of genericity). You won't be able to use an index, here.

相关文章