Reputation: 929
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!
Upvotes: 2
Views: 5895
Reputation: 227578
In this call:
return merge(left_merged, merge_sort(right));
the second argument is a temporary, and you cannot bing a non-const reference to a temporary. You need
vector<int> merge(vector<int>& left, const vector<int>& right);
and probably (although it wouldn't affect this particular example),
vector<int> merge(const vector<int>& left, const vector<int>& right);
If you find yourself making copies of the arguments inside the functions, you could take them by value. For example, in case you were copying the second argument, then prefer this:
vector<int> merge(const vector<int>& left, vector<int> right);.
Upvotes: 3
Reputation: 103751
Change the parameter type, either to const vector<int>&
(const reference), or simply vector<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.
Upvotes: 3