要迭代或使用计数器,这就是问题 [英] To iterate or to use a counter, that is the question

查看:182
本文介绍了要迭代或使用计数器,这就是问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当有人开始使用STL并且他们有一个向量,你通常会看到:

Whenever someone starts using the STL and they have a vector, you usually see:


vector<int> vec ;

//... code ...

for( vector<int>::iterator iter = vec.begin() ;
     iter != vec.end() ;
     ++iter )
{
  // do stuff
}

我只是发现整个向量< int> :: iterator 语法晕眩。我知道你可以 typedef vector< int> :: iterator VecIterInt 稍微好一点。

I just find that whole vector<int>::iterator syntax sickitating. I know you can typedef vector<int>::iterator VecIterInt, and that is slightly better..

但问题是,好的ol'有什么问题:

But the question is, what's wrong with good ol':


for( int i = 0 ; i < vec.size() ; i++ )
{
  // code
}


推荐答案

当您使用索引执行基本的顺序访问容器( std :: vector 实际上你不需要在你的算法中使用这种访​​问方式,将随机访问要求强加在底层数据结构上。与顺序存取的要求相比,随机存取要求是相当强烈的要求。强烈的需求没有很好的理由是一个主要的设计错误。

When you use index to perform essentially sequential access to a container (std::vector or anything else) you are imposing the random-access requirement onto the underlying data structure, when in fact you don't need this kind of access in your algorithm. Random-access requirement is pretty strong requirement, compared to a significantly weaker requirement of sequential access. Imposing the stronger requirement without a good reason is a major design error.

所以正确的答案,你的问题是:使用顺序(迭代器)访问,无论什么时候, (索引)访问只有当你绝对有。尽量避免使用索引访问。

So the correct answer to your question is: use sequential (iterator) access whenever you can, use random (index) access only when you absolutely have to. Try to avoid index access whenever possible.

如果您的算法严格依赖于随机访问的容器,算法。在这种情况下,您可以使用索引访问,无需任何预留。但是,如果只使用迭代器可以实现相同的算法,那么只有坚持迭代器,即完全依赖顺序访问是一个好习惯。

If your algorithm critically relies on the container being random-accessible, it becomes the external requirement of the algorithm. In this case you can use index access without any reservations. However, if it is possible to implement the same algorithm using iterators only, it is a good practice to stick to iterators only, i.e. exclusively rely on sequential access.

当然,上述规则,虽然为真,但在代码中是有意义的泛型在一定程度上。如果代码的某些其他部分是特定的,那么你确定你正在使用的数据结构是 std :: vector 并且将始终是 std :: vector ,则访问方法不再重要。使用任何你喜欢的。但是,在顺序访问完全足够的情况下,我仍然可以避免索引访问。

Of course, the above rule, while true, only makes sense in the code is generic to a certain degree. If some other portion of the code is so specific, that you know for sure that the data structure you are working with is a std::vector and will always be a std::vector, then the access method no longer matters. Use whatever you prefer. However, I would still avoid index access in situations when sequential access is perfectly sufficient.

这篇关于要迭代或使用计数器,这就是问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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