0

The code on top works. The code below it does not. Why?

I am searching through a vector of class objects in C++ using the object's name member so as to increment it's watched member. The regular for loop and syntax successfully increments the member. However, my attempt to do the same using what I assumed was the correct syntax for a range based for loop is unsuccessful. What is the correct syntax to make it successful?

   //This works
   for(size_t i{0}; i<mList.size(); ++i)
   {
      if(mList.at(i).name == name_val)
      {
         mList.at(i).watched += 1;//Successfully increments member of the object
         return;
      }
   }

   //This does not work
     for(auto m : mList)
   {
      if(m.name == name_val)//This if clause does appear to work though..
      {                     //..in a different function.
         m.watched += 1;//But this here is not incrementing the object member
         return;
      }
   }

BTW, if it makes a difference, these loops are inside of a method that along with the vector are members of a friend class to the class of objects in the vector. And I have also already tried ++m.watched; and ++(m.watched); without success. Thank you

Seth Van
  • 25
  • 7

1 Answers1

4

Your loop makes a copy of the element into m every iteration. Your changes to m will be to that copy. Make m a reference to the element in the container instead:

     for(auto& m : mList)
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27