My first time posting here and hope i don't make a fool of myself! |
You're one of the very few who use code tags in their first posts, very good impression so far.
Yes, it's because of the pass by reference thing. In function 1, the vector is being copied and the operation is being performed on the copied vector, so when you print out the vector in main, nothing has changed since you didnt do anything with the original vector, but rather the copy.
In the second function, since you pass it by reference, you're passing the original vector and the operations in there take place on it, so when you print it out in main, the changes done to the vector will be made.
And one one question: While reading on the web about this some states that its bad programing to use a reference with vectors but my program compiles just fine (c++11)? Is it bad programing to write f2(vector<double>& v2)? |
Personally Ive never heard this, I'm not an expert though so someone else is going to have to shed some extra light. But passing by reference is very useful and indeed needed, especially when there are big data objects, it can be very expensive making copies, same thing regarding returning by reference.
For example, I'm making a 3D Application, and I have models loaded in. Whenever I want to use one of the models, if my function that returns the model does not return it by reference but rather by value, my applications fps drops to about 60. When I later changed it to return by reference, the fps went up to something like 400.