For range loop question

Halo

i am wondering about the For range loop with a class.
it a little bit confused me..

1
2
3
4
5
6
7
8
9
10
11
  bool Movies::increment_watched(std::string name){
    for(Movie &m: movies){
        if(m.get_name() == name){
            m.increment_watched();
            return true;
          } else {
        std::cout << " The movie is not exist in the list" << std::endl;
        return false;
          }
    }         
}

this code is part of a bigger code that let the user add movies to a vector (movies) and to increment the number of time the movie been watched.

1.in that part: "for(Movie &m: movies)" what is the "m" ? a variable or a
object of class Movie?
if "m" is an object so an constructor is been calling yes? also copy
constructor?
2. if instead of the class name "Movie" i will put "auto" it will
be the same?
3. why we needed the reference before the "m" in this case?


thank you
You may want to look up Ranged based loops for the answer to these questions.

Here is but one example:

https://www.geeksforgeeks.org/range-based-loop-c/
1
2
3
4
5
6
void foo(Movie &m);

int answer = 42;
int &bar = answer;

T &sdf1 = *v.begin();

¿what does the & mean in those examples?


> if instead of the class name "Movie" i will put "auto" it will be the same?
try it.
if you're asking about good programming practices, then `auto' is less error-prone.


PS: having classes `Movie' and `Movies' will get you blind
1) m is a Movie here. No constructor is called, it's exactly the same than the ones in your vector.

2) Yes. Like said above, auto is less error-pprone, but I personnally prefer to always know my types.

3) You need a reference because it seems that the increment_watched() function modify the object. If you don't pass a reference, it will modify a copy (so nothing).
Note that sometimes you can pass const & on big objects (actually everything which is bigger than a long long type) to save memory space without modifying the object.
Topic archived. No new replies allowed.