Search code examples
c++for-loopc++11stdvectorrange-based-loop

Why is this working in a normal for loop but not a range based for loop?


void set_fee(Patron p, int fee)
{
    for (Patron x : patrons)
    {
        if (p.get_name() == x.get_name()) x.set_fee(fee);
    }
    
    for (int i = 0; i < patrons.size(); i++)
    {
        if (patrons[i].get_name() == p.get_name()) patrons[i].set_fee(fee);
    }
}

So patron is just some class I made and none of the functions here really matter get_name() just returns the object's name and set_fee(fee) just sets the fee of the object to fee.

But does anyone have any idea for why the first loop doesn't work but the second one does? I basically just wanna look for p inside the patrons vector and once I find it I want to change the fee of the patron object inside the vector, but the first way doesn't work, why?


Solution

  • Your x in the range based for loop is a copy of the element in the vector. You need to have reference there

    for (Patron& x : patrons)
    //   ^^^^^^^^
    {
       // ....
    }
    

    or else x.set_fee(fee); will be called on the copy.