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 容器的方法更好?
基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
