C++ STL: Which method of iteration over a STL container is better?(C++ STL:哪种迭代 STL 容器的方法更好?)
问题描述
这对你们中的一些人来说可能看起来很无聊,但是以下两种对 STL 容器进行迭代的方法中哪一种更好?为什么?
This may seem frivolous to some of you, but which of the following 2 methods of iteration over a STL container is better? Why?
class Elem;
typedef vector<Elem> ElemVec;
ElemVec elemVec;
// Method 0
for (ElemVec::iterator i = elemVec.begin(); i != elemVec.end(); ++i)
{
Elem& e = *i;
// Do something
}
// Method 1
for (int i = 0; i < elemVec.size(); ++i)
{
Elem& e = elemVec.at(i);
// Do something
}
方法 0 看起来像更简洁的 STL,但方法 1 用更少的代码实现了相同的效果.对容器的简单迭代是all 出现在任何源代码中的位置.所以,我倾向于选择方法 1,它似乎可以减少视觉混乱和代码大小.
Method 0 seems like cleaner STL, but Method 1 achieves the same with lesser code. Simple iteration over a container is what appears all over the place in any source code. So, I'm inclined to pick Method 1 which seems to reduce visual clutter and code size.
PS:我知道迭代器可以做的不仅仅是一个简单的索引.但是,请保持回复/讨论的重点是对容器的简单迭代,如上所示.
PS: I know iterators can do much more than a simple index. But, please keep the reply/discussion focused on simple iteration over a container like shown above.
推荐答案
第一个版本适用于任何容器,因此在将任何容器作为参数的模板函数中更有用.可以想象,它的效率也会稍高一些,即使对于向量也是如此.
The first version works with any container and so is more useful in template functions that take any container a s a parameter. It is also conceivably slightly more efficient, even for vectors.
第二个版本仅适用于向量和其他整数索引容器.对于那些容器来说,它会更惯用一些,C++ 新手很容易理解,如果您需要对索引做其他事情,这很有用,这并不少见.
The second version only works for vectors and other integer-indexed containers. It'd somewhat more idiomatic for those containers, will be easily understood by newcomers to C++, and is useful if you need to do something else with the index, which is not uncommon.
像往常一样,恐怕没有简单的这个更好"的答案.
As usual, there is no simple "this one is better" answer, I'm afraid.
这篇关于C++ STL:哪种迭代 STL 容器的方法更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ STL:哪种迭代 STL 容器的方法更好?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
