How to directly use vector as parameter in a function?

I know how to initilize a new vector before using it, but how to convenitently use it as paramter in a function?
For example, when I init v1, it can get result in the end, but when I use v2, it shows error :cannot use this type name.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
    vector<int> Add(vector<int>&nums, int target)
        cout << nums[0] + target;

int main(){
    Solution Sol1;
    vector <int> v1 {1,2,3};
    Sol1.add(v1, 8);
    Sol1.add(vector <int> v2{4,5,6}, 8);

Besides, I tried to correct v2 as Sol1.add(vector <int> {4,5,6}, 8); However, it shows error: The initial value of a non-constant reference must be an left value

>Solution :

The problem you are having has nothing to do with vector.

Sol1.add(vector<int> v2{4,5,6}, 8);

Here, it seems like you are trying to declare an object name v2 in the middle of this expression, which isn’t something you can do in C++.

However, you can create a unnamed temporary object in the middle of it like:

Sol1.add(vector<int>{4,5,6}, 8);

or even:

Sol1.add({4,5,6}, 8);

But now you would face a different problem, like you mentioned:

The initial value of a non-constant reference must be an left value

The reason for that is you can’t create a reference to a temporary object. To solve it, you can either copy the vector to your function, by changing the signature of your add function:

vector<int> add(vector<int> nums, int target)

However, this solution need to copy the entire vector to the function, hence it might be quite slow if your vector is large. Another way is to change the signature to const reference of a vector, which can bond to a temporary object. The downside is that you will not be able to modify the object inside the function, if you were looking to do that:

vector<int> add(const vector<int>& nums, int target)

Leave a Reply