[英]accessing a specific point of a vector with an iterator
I am trying to figure out the best way of accessing a position in a vector using an iterator. 我试图找出使用迭代器访问向量中位置的最佳方法。 I'm aware iterators behave like pointers, so this is the only method I came up with.
我知道迭代器的行为类似于指针,因此这是我想到的唯一方法。 I would like to know if there's a better or just a different way.
我想知道是否有更好的方法或只是另外一种方法。 Here's the code:
这是代码:
//This is a pointer to a vector of the class Particle BTW. vector < Particle > *particleList;
vector<Particle>::iterator it = particleList->begin();
// I assign a specific position outside the loop to a new iterator that won't be affected
vector<Particle>::iterator it2 = particleList->begin() + 3;
for( it; it != particleList->end(); it++){
it->draw();
//I'm interested in the velocity of this element in particular
cout << it2->vel << endl;
}
Thanks, 谢谢,
M 中号
Try the following 尝试以下
for (auto i = particleList->begin(); i < particleList->begin(); ++i) {
i->draw();
std::cout << (i+3)->vel << "\n";
}
Note, there is no reason to use std::endl
, std::endl
has an implicit flush which lowers performance when outputting to say a log file, and when outputting to console it is already line buffered meaning that a line ending will already flush. 注意,没有理由使用
std::endl
, std::endl
具有隐式刷新,这会降低输出,例如输出日志文件时的性能;输出到控制台时,它已经是行缓冲的,这意味着行尾将已经刷新。
Note 2, you can only use +
with i
since i
is a random access iterator because particleList
is a std::vector
, if you change say particleList
to a std::list
then the iterator will be a bidirectional iterator instead of a random access iterator and you will not be able to use +
in that case you would need to use std::advance
like WhozCraig mentioned, but do so on a copy like so: 注2,你只能使用
+
与i
,因为i
是一个随机访问迭代,因为particleList
是std::vector
,如果你改变说particleList
到std::list
,然后迭代器将是一个双向迭代器,而不是随机访问迭代器,在这种情况下您将无法使用+
,您将需要使用std::advance
如WhozCraig所提到的那样,但是在类似这样的副本上这样做:
for (auto i = particleList->begin(); i < particleList->begin(); ++i) {
i->draw();
auto i2 = i;
std::advance(i2, 3)
std::cout << i2->vel << "\n";
}
Though personally, in this case I would just iterate with two iterators instead of std::advance
since std::advance
is linear in time. 尽管个人而言,在这种情况下,我将只使用两个迭代器而不是
std::advance
进行迭代,因为std::advance
在时间上是线性的。 Do something like: 做类似的事情:
auto i = particleList->begin();
auto i2 = particleList->begin();
std::advance(i2, 3);
for (; i < particleList->end(); ++i, ++i2) {
i->draw();
std::cout << i2->vel << "\n";
}
Note 3: (i+3)
and i2
will run off the end of your list (vector), so do something smart there. 注意3:
(i+3)
和i2
会从列表(向量)的末尾开始,所以在此做一些聪明的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.