C++ STL:如何在需要访问元素及其索引的同时迭代向量?
我经常发现自己需要迭代 STL 向量。当我这样做时,我需要访问向量元素及其索引。
我曾经这样做过:
typedef std::vector<Foo> FooVec;
typedef FooVec::iterator FooVecIter;
FooVec fooVec;
int index = 0;
for (FooVecIter i = fooVec.begin(); i != fooVec.end(); ++i, ++index)
{
Foo& foo = *i;
if (foo.somethingIsTrue()) // True for most elements
std::cout << index << ": " << foo << std::endl;
}
在发现 BOOST_FOREACH 之后,我将其缩短为:
typedef std::vector<Foo> FooVec;
FooVec fooVec;
int index = -1;
BOOST_FOREACH( Foo& foo, fooVec )
{
++index;
if (foo.somethingIsTrue()) // True for most elements
std::cout << index << ": " << foo << std::endl;
}
当需要引用向量元素及其索引时,是否有更好或更优雅的方式来迭代 STL 向量?
我知道另一种选择: for (int i = 0; i < fooVec.size(); ++i) 但我一直在阅读关于迭代 STL 不是一个好的做法像这样的容器。
I frequently find myself requiring to iterate over STL vectors. While I am doing this I require access to both the vector element and its index.
I used to do this as:
typedef std::vector<Foo> FooVec;
typedef FooVec::iterator FooVecIter;
FooVec fooVec;
int index = 0;
for (FooVecIter i = fooVec.begin(); i != fooVec.end(); ++i, ++index)
{
Foo& foo = *i;
if (foo.somethingIsTrue()) // True for most elements
std::cout << index << ": " << foo << std::endl;
}
After discovering BOOST_FOREACH, I shortened this to:
typedef std::vector<Foo> FooVec;
FooVec fooVec;
int index = -1;
BOOST_FOREACH( Foo& foo, fooVec )
{
++index;
if (foo.somethingIsTrue()) // True for most elements
std::cout << index << ": " << foo << std::endl;
}
Is there a better or more elegant way to iterate over STL vectors when both reference to the vector element and its index is required?
I am aware of the alternative: for (int i = 0; i < fooVec.size(); ++i)
But I keep reading about how it is not a good practice to iterate over STL containers like this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
向量是 C 数组的薄包装;无论您使用迭代器还是索引,它都一样快。但其他数据结构就不那么宽容了,例如 std::list。
Vectors are a thin wrapper over C arrays; whether you use iterators or indexes, it's just as fast. Other data structures are not so forgiving though, for example std::list.
您始终可以在循环中计算索引:
对于向量,这很可能被实现为单个指针减法运算,因此它并不是特别昂贵。
You can always compute the index in the loop:
For a vector, this is quite likely to be implemented as a single pointer subtraction operation, so it's not particularly expensive.
优雅在于情人眼里,但请记住指针/迭代器算术:)
与距离方法相比,好处是您不会错误地对非 random_access_iterator 执行此操作,因此您将始终处于 < em>O(1)。
Elegance is in the eye of the beholder, however do remember pointer/iterator arithmetics :)
The up-side compared to the distance method is that you won't mistakenly do this for a non-random_access_iterator, so you'll always be in O(1).
对于具体问题:
恕我直言,
是最简单和优雅的解决方案。根据问题的要求,不需要使用迭代器。
For the specific question:
IMHO,
is the most simple and elegant solution. Per the requirements of the question, using an iterator is not required.