时间:2019-05-09 标签:c++vectorobject.erase [英] c++ vector object .erase

查看:23
本文介绍了时间:2019-05-09 标签:c++vectorobject.erase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力将矢量对象放入我正在做的项目中我已经阅读了我能找到的关于这样做的内容,并决定试一试.

I have been struggling to put a vector object into a project im doing I have read what little i could find about doing this and decided to give it a go.

      std::vector<BrickFalling> fell;
      BrickFalling *f1;

我创建了矢量.下一块工作正常,直到我擦除部分.

I created the vector. This next piece works fine until i get to the erase section.

if(brickFall == true){

f1 = new BrickFalling;

f1->getBrickXY(brickfallx,brickfally);

fell.push_back(*f1);
brickFall = false;
}
// Now setup an iterator loop through the vector

vector<BrickFalling>::iterator it;

for( it = fell.begin(); it != fell.end(); ++it ) {

   // For each BrickFalling, print out their info

   it->printBrickFallingInfo(brick,window,deadBrick);

   //This is the part im doing wrong /////
   if(deadBrick == true)// if dead brick erase
   {
       BrickFalling[it].erase;//not sure what im supposed to be doing here
       deadBrick = false;
   }
}

推荐答案

应尽可能使用详细说明 remove_if 使用的另一个答案.但是,如果您的情况不允许您使用 remove_if 编写代码(这可能发生在更复杂的情况下),您可以使用以下内容:

The other answer detailing the use of remove_if should be used whenever possible. If, however, your situations does not allow you to write your code using remove_if, which can happen in more complicated situations, you can use the following:

您可以使用带有迭代器的 vector::erase 来删除该位置的元素.然后使用的迭代器无效.erase 返回一个指向下一个元素的新迭代器,因此您可以使用该迭代器继续.

You can use vector::erase with an iterator to remove the element at that spot. The iterator used is then invalidated. erase returns a new iterator that points to the next element, so you can use that iterator to continue.

你最终得到的是一个循环:

What you end up with is a loop like:

for( it = fell.begin(); it != fell.end(); /* iterator updated in loop */ )
{
     if (shouldDelete)
         it = fell.erase(it);
     else
         ++it;
}

这篇关于时间:2019-05-09 标签:c++vectorobject.erase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆