Ways to Passing Vector to a Function in C++ coding

 

When we move an array to a operate, a pointer is definitely handed. However, to move a vector there are two methods to take action:

  1. Pass By worth
  2. Pass By Reference

When a vector is handed to a operate, a replica of the vector is created. This new copy of the vector is then used within the operate and thus, any modifications made to the vector within the operate don’t have an effect on the unique vector.

For instance, we will see beneath this system, modifications made contained in the operate will not be mirrored outdoors as a result of the operate has a replica.

Example(Pass By Value):

 

CPP

#include <bits/stdc++.h>

using namespace std;

 

void func(vector<int> vect) { vect.push_back(30); }

 

int main()

{

    vector<int> vect;

    vect.push_back(10);

    vect.push_back(20);

 

    func(vect);

 

    

    

    for (int i = 0; i < vect.size(); i++)

        cout << vect[i] << " ";

 

    return 0;

}

Passing by worth retains the unique vector unchanged and doesn’t modify the unique values of the vector. However, the above model of passing may also take quite a lot of time in circumstances of huge vectors. So, it’s a good suggestion to move by reference.

Example(Pass By Reference):

CPP

#include <bits/stdc++.h>

using namespace std;

 

void func(vector<int>& vect) { vect.push_back(30); }

 

int main()

{

    vector<int> vect;

    vect.push_back(10);

    vect.push_back(20);

 

    func(vect);

 

    for (int i = 0; i < vect.size(); i++)

        cout << vect[i] << " ";

 

    return 0;

}

Passing by reference saves quite a lot of time and makes the implementation of the code quicker.

Note: If we don’t need a operate to switch a vector, we will move it as a const reference additionally.

CPP

#include<bits/stdc++.h> 

using namespace std; 

 

void func(const vector<int> &vect) 

    

                            

    

    

    

     

    for (int i = 0; i < vect.size(); i++) 

    cout << vect[i] << " "

 

int main() 

    vector<int> vect; 

    vect.push_back(10); 

    vect.push_back(20); 

 

    func(vect); 

     

    return 0; 

}

This article is contributed by Kartik. If you want GeeksforGeeks and wish to contribute, you too can write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article showing on the GeeksforGeeks main web page and assist different Geeks. Please write feedback in the event you discover something incorrect, otherwise you need to share extra details about the subject mentioned above.

 

Add a Comment

Your email address will not be published. Required fields are marked *