Note that there are some explanatory texts on larger screens.

plurals
  1. PODelete and add elements to vector inside main loop
    primarykey
    data
    text
    <p>I searched before but couldn't find any answers. I am somewhat new to c++, so hopefully this question won't be too stupid.</p> <p>I am trying to add and remove elements in a vector, in my case populated with particles during a big update or drawing loop over all particles. For example remove some particles because they died, but also add a few other ones because one particle collided with an object and I want to show a small particle burst at the point of collision. I made this simple test code in a demo file to get to the bottom of the problem. </p> <p>I think the problem is since I delete and add particles the iterator pointer becomes invalid. Deletion works, but when I add a few random ones I get a null pointer. the code below is somewhat verbose, I know I should use iterators with begin() and end() but I had the same problem with those, and played with the code a bit, trying more javascript array style looping because I am more familiar with that.</p> <pre><code>void testApp::drawParticles() { int i=0; int max = particles.size(); vector&lt;Particle*&gt;::iterator it = particles.begin(); while ( i &lt; max ) { Particle * p = particles[i]; if ( ofRandom(1) &gt; .9 ) { it = particles.erase(it); max = particles.size(); } else { ofSetColor(255, 255, 0); ofCircle( p-&gt;x, p-&gt;y, p-&gt;z, 10); if ( ofRandom(1) &lt; .1 ) addSomeNewOnes(); i++; it++; } } } void testApp::addSomeNewOnes() { int max = ofRandom(4); for ( int i=0; i&lt;max; i++ ) { Particle * p = new Particle(); p-&gt;x = ofRandom( -ofGetWidth()/2, ofGetWidth()/2 ); p-&gt;y = ofRandom( -ofGetHeight()/2, ofGetHeight()/2 ); p-&gt;z = ofRandom( -ofGetHeight()/2, ofGetHeight()/2 ); particles.push_back( p ); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload