使用迭代器访问向量的特定点

时间:2013-10-31 02:33:18

标签: c++ vector iterator

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

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

谢谢,

中号

1 个答案:

答案 0 :(得分:1)

尝试以下

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

注意,没有理由使用std::endlstd::endl有一个隐式刷新,当输出说日志文件时会降低性能,当输出到控制台时,它已经是行缓冲的,这意味着行尾已经冲洗了。

注意2,您只能将+i一起使用,因为i是随机访问迭代器,因为particleListstd::vector,如果您更改说particleListstd::list然后迭代器将是双向迭代器而不是随机访问迭代器,在这种情况下你将无法使用+你需要使用{{1}像WhozCraig提到的那样,但是在这样的副本上这样做:

std::advance

虽然就个人而言,在这种情况下,我只会使用两个迭代器而不是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

注意3: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"; } (i+3)将在列表末尾(向量)运行,因此请执行智能操作。