I have been playing around with vectors and writing my own function that prints their elements. This function is straightforward to code, but I noticed a small detail which I cannot explain.
Say I have the following function that prints the elements (I'm only shown the declaration here)
void print(vector<int> vec);
And that I have another function that creates and returns a vector:
vector<int> create_vector( //parameters);
And lastly, say in my main function I wanted to run something along the lines of
print(create_vector(// some paramters));
I noticed this works. What also works is if I pass my vector into my print
function as a constant reference:
void print(const vector<int>& vec);
However, what does not work is if I simply pass it by reference
void print(vector<int>& vec);
and I get the following error:
error: cannot bind non-const lvalue reference of type ‘std::vector&’ to an rvalue of type ‘std::vector’
I would think this is because I am trying to print a variable that has not yet been realized, but if that's the case how come it works when passed as a constant reference?