2

There's something about & usage that confuse me it has

vector<int> nums
vector<int>& nums
vector<int> &nums

I am not sure about the difference between them.

class Solution {
public:
    int maxArea(vector<int>& height) {
        long i = 0;
        int j = (height.size() - 1);
        long water = 0;
        while (i < j) {
            water = max(water, ((j - i) * min(height[i], height[j])));
            if (height[i] < height[j]) {
                i += 1;
            } else {
                j -= 1;
            }
        }
        return water;
    }
};

above answer pass with or without the & in LeetCode, why should we need to care about &

littlefish
  • 71
  • 6
  • 2
    Whitespace is not significant in C++. You can also write `vector&nums` or `vector < int > & nums` – molbdnilo May 20 '21 at 09:34
  • 1
    this is related: https://stackoverflow.com/questions/270408/is-it-better-in-c-to-pass-by-value-or-pass-by-constant-reference, though you might need this before https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value – 463035818_is_not_an_ai May 20 '21 at 09:35
  • 1
    Because you should care about passing arguments _by value_ and _by reference_. – Daniel Langr May 20 '21 at 09:35
  • @molbdnilo Oh yeah thats true, thank you very much – littlefish May 20 '21 at 09:36
  • Passing an argument by non-`const` reference (i.e. the `&` and no `const` keyword) allows the function to change the argument passed by the caller. Passing it by value (without the `&`) means that the function receives a copy of the object passed by the caller, so (if the function changes that argument) those changes affect the copy, and are not visible to the caller. The placing of whitespace is irrelevant (i.e. `vector& nums` and `vector &nums` are equivalent). – Peter May 20 '21 at 09:36
  • 3
    tbh this is something so fundamental that one shold learn it before jumping into coding challenges. Leetcode is not the place to learn the basics of C++. – 463035818_is_not_an_ai May 20 '21 at 09:36

1 Answers1

3
vector<int> nums
//The below two are identical:
vector<int>& nums
vector<int> &nums

The code will work if you include or exclude the & but a parameter with & accepts a reference to the same variable to the function and prevents copying of the vector from the calling function to the called function. This is to improve performance and prevent the copying overhead. References almost work the same as pointers.

If you are using it as a variable instead of a function parameter, assigning to it is mandatory and once assigned, the reference cannot be changed to refer to another variable.

This would mean if you modify the height vector in the function, the vector in the calling function will also be modified. To prevent modification, use:

int maxArea(const vector<int>& height) 
Amal K
  • 4,359
  • 2
  • 22
  • 44