×

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector:

  • Pass by Value
  • Pass by Reference

A copy of a vector is made when a vector is handed to a function. As a result, any modifications performed to the vector in the process do not alter the original vector. This new copy of the vector is then used in the function.

For instance, changes performed inside a function are not reflected outside because the position has a copy, as we can see the following program.

Pass By Value

#include <bits/stdc++.h>
using namespace std;


// making a function that receives a vector of values as input


void func(vector <int> duplicate) { //The primary vector is duplicated in the secondary      
// Allow me to multiply each even value in the vector by 1.
     int l = duplicate.size(); // saving the vector duplicate's size in l


     // dividing each duplicate even number by 1
     for(int i = 0; i < l; i++){
         if(duplicate[i]%2 == 0)
          duplicate[i]--;
     }


     // showing the altered vector
     cout<<"Modified vector in the function-->"<<endl;
     for(int i = 0;i < l;i++)
      cout<<duplicate[i]<<" ";
    cout<<endl;
}


int main(){
    vector <int> original = {1,2,3,4,5,6,7,8,10}; // the original vector's creation


    func( original ); // utilising the func function


    cout<<endl<<"Original vector is-->"<<endl;
    for(int i=0;i<original.size();i++)
     cout<<original[i]<<" ";


    return 0;
}

Output:

Passing a Vector to a function in C++

The original vector is kept intact, and its initial values are not modified by passing by value. However, when dealing with significant vectors, the passing method described above may also take a long time. So, passing by reference is a wise move.

Pass By Reference

A vector passed by reference causes the function to work with the original vector rather than a copy of it. As a result, any modifications made to the function's vector are also permanent or reflect themselves in the initial vector.

Additionally, because it doesn't make a new copy, passing by reference is faster and uses less time and space.

Reference Passing is required for following:

  • To alter the initial vector.
  • To speed up the code in specific circumstances. For instance, it is preferable to pass by reference when the function does not modify the vector to speed up the code.

Example:

#include <bits/stdc++.h>
using namespace std;


// making a function that allows the vector to be passed by reference


void func( vector <int>&duplicate) {  // By reference, the initial vector is passed
     // Allow me to multiply each even value in the vector by 1.
     int l = duplicate.size(); // saving the vector duplicate's size in l


     // dividing each duplicate even number by 1
     for(int i = 0; i < l; i++){
         if(duplicate[i]%2 == 0)
          duplicate[i]--;
     }


     // showing the altered vector
     cout<<"Modified vector in the function-->"<<endl;
     for(int i = 0;i < l;i++)
      cout<<duplicate[i]<<" ";
    cout<<endl;
}


int main(){
    vector <int> original = {1,2,3,4,5,6,7,8,10}; // the original vector's creation


    func( original ); // utilising the func function


    cout<<endl<<"Original vector is-->"<<endl;
    for(int i=0;i<original.size();i++)
     cout<<original[i]<<" ";


    return 0;
}

Output:

Passing a Vector to a function in C++

Because, we passed the original vector to the function by reference using the & operator in the code above, we can see that after modifying the vector in the function, the changes are also reflected in the original vector.

// Vectors can be passed by reference with restrictions using a C++ application that shows how.
#include<bits/stdc++.h> 
using namespace std; 
// This function cannot alter the fact because it is passed by constant reference
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; 
}

Output:

Passing a Vector to a function in C++

Passing the function, a global vector

Any function in the program can access a global vector, which is a vector that is declared outside the primary role. We do not need to send the vector to the function since any process that accesses a global vector has the ability to alter the original vector.This indicates that the initial vector is utilized in this application rather than a clone.


Related Topics

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

Sizeof() Operators in C++

sizeof() Operators in C++ The sizeof() operator in C++ defines the size of variables, constants, or data types. It is a unique operator that manipulates other operators and returns the size...

4 minutes read.

C++ Overloading

C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types: Function...

1 minute read.

SET Data Structure in C++

Generally, in our home, we store food items in a fridge or kitchen efficiently to find them easily and use them. Similarly, in programming, we need to store the data...

6 minutes read.

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 minutes read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

Hospital Management Project in C++

The following capabilities are required to build a hospital management project: These are as follows: hospitals' names, contact information, and lists of doctors and patients. Activities Supported Hospital Data Print Patients' data to...

4 minutes read.

C++ Pointer

Pointer is a derived data type that stores the address of a variable. A pointer is used for memory management and dynamic memory allocation. Pointer works on the address of data rather than...

2 minutes read.

Function Pointer in C++

Definition: A function pointer in C++ is the same as a usual pointer which is used to point some variables. Function pointers are used to point functions or say store the...

4 minutes read.

Decimal to Octal in C++

We must create a software that converts a decimal number into an equal octal number given a decimal number as input i.e. convert a number having a base value of...

3 minutes read.

Auto keyword in C++

The primary function of auto keyword is to assign and detect the value of the data type automatically in C++. The compiler knows the data type of the variable by...

2 minutes read.

The Stock Span Problem

It is necessary to determine the span of a stock's price throughout all n days in order to solve the stock span problem, which involves a set of n daily...

5 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

C++ Void Pointer

A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type. Void Pointer Syntax: void *ptr;  We can't...

2 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

3 minutes read.