迭代器为什么使用它们? [英] Iterators.. why use them?

查看:109
本文介绍了迭代器为什么使用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在STL库中,一些容器有迭代器,通常认为它们是通过这些容器迭代的优越方式,而不是简单的循环

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

..

}任何人都可以告诉我为什么,在什么情况下,我应该使用迭代器,在什么情况下,上面的代码段?

解决方案

注意,通常vector的实现不会使用int作为索引/大小的类型。因此,您的代码至少会引起编译器警告。



通用性



迭代器增加代码的一般性。



例如:

  typedef std :: vector< int> ;容器 ; 

void doSomething(Container& p_aC)
{
for(Container :: iterator it = p_aC.begin(),itEnd = p_aC.end(); it! itEnd; ++ it)
{
int& i = * it; // i现在是对迭代值的引用
//使用i执行操作
}
}

现在,让我们想象你将向量变成列表(因为在你的情况下,列表现在更好了)。您只需要更改typedef声明,并重新编译代码。



如果您已经使用基于索引的代码,则需要重新编写。 / p>

访问



迭代器应该被视为一种超级指针。
它指向的值(或者,如果是地图,对的键/值对)。



但它有方法移动容器中的下一项。或以前。一些容器甚至提供了随机访问(向量和deque)。



算法



大多数STL算法迭代器或迭代器范围(同样,由于一般性)。您将无法在此使用索引。


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?

解决方案

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.

Genericity

Iterators increase the genericity of your code.

For example:

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"
    }
}

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.

Access

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).

Algorithms

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.

这篇关于迭代器为什么使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆