簡體   English   中英

向量中std :: vector :: iterator的索引是什么?

[英]What is the std::vector::iterator's index in the vector?

我有一個std::vector<Bullet> bullets ,在下面的for循環中,如果它不再存在,我想從向量中刪除項目符號。

我的計划是使用pop_back()刪除元素。 如果向量中有多個元素,我想先將要刪除的元素與向量中的最后一個元素交換,然后調用pop_back()

for (std::vector<Bullet>::iterator b = bullets.begin(); b != bullets.end(); ++b) {
  if(!b->isAlive()) {
    if (bullets.size() > 1) {
      std::iter_swap(bullets + ..., bullets.end());
    }
    bullets.pop_back();
  }
}

問題是iter_swap的第一個參數。 我查找了http://www.cplusplus.com/reference/algorithm/iter_swap/ ,第一個參數的語法是向量+元素的位置。

如何找出向量中b的索引?

有一種更簡單的方法來過濾std::vector

#include <algorithm>

auto part = std::remove_if(
    bullets_.begin(),
    bullets_.end(),
    [](const Bullet &bullet) { return !bullet.isAlive(); });
bullets_.erase(part, bullets_.end());

這會將矢量划分為有生命的和無生命的項目符號,然后刪除包含有無生命的項目符號的段。

std::remove_if()函數類似於partition()但僅保留第一個分區的順序。

如果控制是否要刪除元素的條件是:

object->isAlive()

然后,您應該使用STL方式進行刪除,即擦除刪除習慣用法:

bullets.erase(std::remove_if(bullets.begin(), bullets.end(), 
[](Bullet const& b) {
   return !b.isAlive(); 
}), bullets.end());

現在,要回答您的特定問題,可以像這樣獲得向量v的迭代器的it索引:

auto indx = std::distance(v.begin(), it); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM