5

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?

0

3 Answers 3

9

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'.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks alot for the help. As you can probably tell I'm quite new to C++, i sat scratching my head at this problem for longer than i would care to admit. Out of curiosity, do you this the most efficient way to iterate over the vector. It will probably contain more than 100k+ Person objects, so i'm just wondering if my way is the best way to do it?
@JamesMclaughlin Looping over so many objects to find the one of interest is going to be inefficient, it might be better if you had a variable holding its index.
But wouldn't I still have to iterate to find the object I wanted?
2

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) {
    ...
}

Comments

1

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) {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.