Vector init and for loop in C++11

hello,

i am just converting to C++11 new conventions with oF09

i am trying to get familiar with the for loop syntax with auto

i used to do :

vector<particle> particles;
for (int i = 0; i < 20 ; i ++) {
    particles.push_back(particle());
    particles.back().setup(posX, posY, width, heiht);
}

i can’t figure out how to do the same with

for ( auto p : particles) {
...
}

thank you

1 Like

Maybe something like:

vector<particle> particles;

particles.resize(20); 

for ( auto p : particles) {
   p.setup(posX, posY, width, heiht);
}
1 Like

the trick is that you need to get a reference to the object in the vector, if you do:

vector<particle> particles;

particles.resize(20); 

for ( auto p : particles) {
   p.setup(posX, posY, width, heiht);
}

you are making a copy and calling setup on that copy, if you want to modify the original in the vector the correct syntax is:

vector<particle> particles;

particles.resize(20); 

for ( auto & p : particles) {
   p.setup(posX, posY, width, heiht);
}

note the & between auto and p that makes p a reference to the object in the vector instead of a copy.

1 Like

Ok i got it ! thanks a lot !

Is this the only way though ?

Also, now what if i want to use the particle index in the loop ?

i would update particle positions for instance like so before C++11

for (int = 0; i < 20; i++) {
    float x0 = i * p.x;
    float y0 = i * p.y;
    float x = ofGetWidth() * ofNoise(time * speed + x0);
    float y = ofGetHeight() * ofNoise(time * speed + y0);
    p.update(x, y);
}

there’s not a very specific syntax in c++ for that, ust create a variable and increment it with each iteration:

auto i = 0;
for ( auto & p : particles) {
    float x0 = i * p.x;
    float y0 = i * p.y;
    float x = ofGetWidth() * ofNoise(time * speed + x0);
    float y = ofGetHeight() * ofNoise(time * speed + y0);
    p.update(x, y);
    i++;
}
1 Like

ok. this is what i ended up using but felt a bit uncomfortable as this seemed a less modern way than using vector index.

thanks a lot

Hum… one more :slight_smile:

I need to check the distance between previous particle and current one. I mean distance between particles[i-1] and particles[i]…

particle * previous = nullptr;
for ( auto & p : particles) {
    if(previous!=nullptr){
        p.distance(*previous)
    }
    previous = &p;
}

ok. Thanks for all your suggestions.
This is getting clearing things a bit.
thanks again