I get the “”Invalid initialization of non-const reference of type ‘std::vector&’ from an rvalue of type ‘std::vector” error for the last last for passing in merge_sort(right) in the 2nd param.
left_merged = merge_sort(left);
// right_merged = merge_sort(right);
return merge(left_merged, merge_sort(right));
Here are the function declarations:
vector<int> merge_sort(vector<int>& vec)
vector<int> merge(vector<int>& left, vector<int>& right)
I’ve been reading up the theory on how the rvalue is a temporary object and is destroyed if it’s not used in an initializer or assigned to a variable but all I really want is a quick and dirty solution to be able to call the function in the parameter.
Any quick solutions?
Thanks!
Change the parameter type, either to
const vector<int>&(const reference), or simplyvector<int>(by value).Prefer the first option (const reference) if inside the function you don’t make any changes to the parameter. Otherwise the second (by value). If, inside the function, you are immediately copying the argument, and then manipulating the copy while ignoring the original, take the argument by value, skip the copy, and just use the argument directly.