James Mclaughlin
James Mclaughlin

Reputation: 702

Iterating over a vector of objects

I am trying to iterate over a vector of objects and perform a simple update function which moves the object 1 pixel to the right each time. However, when I run the code, the x value is only changed once.

In source.cpp:

 for (int i = 0; i < Screen::SCREEN_WIDTH * Screen::SCREEN_HEIGHT; i++) {
    people.push_back(Person());
}

for (int i = 0; i < 1; i++) {
    people[i].isAlive = true;
}

while(true) {

 for (Person p : people) {
        if (p.isAlive == true) {
            p.Update(p);
            cout << p.x << endl;
            screen.setPixel(p.x, p.y, 255, 0, 0);
        }
        else {
            screen.setPixel(p.x, p.y, 0, 0, 0);
        }
    }
 }

In person.cpp

 void Person::Update(Person &person) {
      person.x += 1;

}

As you can see, i select one person from the array and set them to be alive, and therefor to be drawn. They are drawn every frame, but not updated. Can anyone help me out with this?

Upvotes: 5

Views: 12847

Answers (3)

Daniel Schepler
Daniel Schepler

Reputation: 3103

for (Person p : people) creates a copy of each element of the vector, and then you are modifying the copy which has no effect on the original object in the vector. What you want would be for (Person& p : people).

Incidentally: you should avoid using endl unless you really need to flush out the output immediately. Instead, in most cases you should just output '\n'.

Upvotes: 9

Steve
Steve

Reputation: 1757

If you want to modify the Person inside your loop, you'll need to use a reference - otherwise you'll be working with a copy of whatever is in the vector, which then gets discarded.

for (Person p : people) {

needs to be

for (Person& p : people) {

Upvotes: 1

Amadeus
Amadeus

Reputation: 10655

In this statement:

for (Person p : people) {
    ...
}

you a making a copy in p object, changing it, and, at the end, destroying it

In order to preserve your changes, do:

for (Person &p : people) {
    ...
}

Upvotes: 2

Related Questions