0

I got a weird compile error in the following code:

class Solution {
public:
    int function(vector<int>& nums) {
        //Did something
        int len = nums.size();
        int mid = len / 2;
        if (nums[mid] < nums[0]) {
            vector<int> newVec(nums.begin(), nums.begin() + mid);
            return function(newVec);
        }
        else 
            return function(vector<int>(nums.begin() + mid + 1, nums.end()));
    }
};

The error occured in: return function(vector<int>(nums.begin() + mid + 1, nums.end()));

It seems to me that it works perfectly fine if I construct the vector first, then pass it to the function. Like what I did in the block under if:

vector<int> newVec(nums.begin(), nums.begin() + mid);
return function(newVec);

But if I combine these two steps, the error occurs. Could anyone please explain that for me? Many thanks~

=========================================================================

Edit:

The compile error was

no matching function for call to ‘Solution::function(std::vector<int>)’

  • Please post the "weird compiler error" message. – PaulMcKenzie Dec 08 '15 at 02:31
  • Just a quick question. It might be because it's 4 AM, but I kinda see an infinite recursion here. Is that weird compiler error a stack overflow? – mrDudePerson Dec 08 '15 at 02:35
  • Duplicate of: http://stackoverflow.com/questions/1565600/how-come-a-non-const-reference-cannot-bind-to-a-temporary-object – PaulMcKenzie Dec 08 '15 at 02:36
  • `vector& nums` is an *lvalue reference*. You must pass an lvalue. To allow both of these uses, change to `vector const &nums` , which you should be doing anyway. – M.M Dec 08 '15 at 02:41
  • Consider redesigning `function` to accept an iterator range in the first place. Then you can run your whole algorithm just looking at a single buffer, instead of making heaps of copies of parts of it. – M.M Dec 08 '15 at 02:42
  • @M.M Thanks. It works! – NameTooLongException Dec 08 '15 at 02:47

1 Answers1

0

vector<int>& nums is an lvalue reference. You must pass an lvalue. To allow both of these uses, change to vector<int> const &nums , which you should be doing anyway.
Consider redesigning function to accept an iterator range in the first place. Then you can run your whole algorithm just looking at a single buffer, instead of making heaps of copies of parts of it.
– M.M

Armali
  • 18,255
  • 14
  • 57
  • 171