[英]What is the std::vector::iterator's index in the vector?
I have an std::vector<Bullet> bullets
and in the for-loop below I want to remove a bullet from the vector if it's not alive anymore. 我有一个
std::vector<Bullet> bullets
,在下面的for循环中,如果它不再存在,我想从向量中删除项目符号。
My plan is to remove the element with pop_back()
. 我的计划是使用
pop_back()
删除元素。 If there are more than one element in the vector I want to first swap the element that is to be removed with the last element in the vector, and then call 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();
}
}
The problem is the first parameter in iter_swap
. 问题是
iter_swap
的第一个参数。 I looked up http://www.cplusplus.com/reference/algorithm/iter_swap/ and the syntax for the first parameter is the vector + the position of the element. 我查找了http://www.cplusplus.com/reference/algorithm/iter_swap/ ,第一个参数的语法是向量+元素的位置。
How do I find out b
's index in the vector? 如何找出向量中
b
的索引?
There's an easier way to filter a std::vector
. 有一种更简单的方法来过滤
std::vector
。
#include <algorithm>
auto part = std::remove_if(
bullets_.begin(),
bullets_.end(),
[](const Bullet &bullet) { return !bullet.isAlive(); });
bullets_.erase(part, bullets_.end());
This will partition the vector into the alive and dead bullets, and then you delete the segment with the dead bullets. 这会将矢量划分为有生命的和无生命的项目符号,然后删除包含有无生命的项目符号的段。
The std::remove_if()
function is like partition()
but only the order of the first partition is preserved. std::remove_if()
函数类似于partition()
但仅保留第一个分区的顺序。
If the condition governing whether an element is to be removed or not is : 如果控制是否要删除元素的条件是:
object->isAlive()
Then you should use an STL way to do the removal, namely the erase-remove idiom : 然后,您应该使用STL方式进行删除,即擦除删除习惯用法:
bullets.erase(std::remove_if(bullets.begin(), bullets.end(),
[](Bullet const& b) {
return !b.isAlive();
}), bullets.end());
Now, to answer your particular question an iterator's it
index in a vector v
can be obtained like so : 现在,要回答您的特定问题,可以像这样获得向量
v
的迭代器的it
索引:
auto indx = std::distance(v.begin(), it);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.