0

我试图找出使用迭代器访问向量中位置的最佳方法。我知道迭代器的行为类似于指针,所以这是我想出的唯一方法。我想知道是否有更好的方式或只是不同的方式。这是代码:

   //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;
}

谢谢,

4

1 回答 1

1

尝试以下

for (auto i = particleList->begin(); i < particleList->begin(); ++i) {
  i->draw();
  std::cout << (i+3)->vel << "\n";
}

请注意,没有理由使用std::endl,std::endl具有隐式刷新,这会在输出到日志文件时降低性能,并且在输出到控制台时它已经是行缓冲的,这意味着行结尾已经刷新。

注意 2,您只能使用+with isincei是随机访问迭代器,因为particleListis a std::vector,如果您将 say 更改particleList为 astd::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";
}

尽管就个人而言,在这种情况下,我只会使用两个迭代器进行迭代,而不是std::advance因为std::advance时间是线性的。执行以下操作:

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";
}

注意 3:(i+3)并且i2会超出列表的末尾(向量),所以在那里做一些聪明的事情。

于 2013-10-31T08:45:01.373 回答