×

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

Structure Sorting (By Multiple Rules) in C++

To understand the concept of Structure Sorting (By Multiple Rules) in C++, it is recommended to know the Structures concept in the C++ programming language. Here the scenario is pretty...

3 minutes read.

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

Approach in C++

Object oriented programming languages like Java or C++ use a bottom-up approach that identifies each object first.  In the bottom-up approach, we create a small problem first, and try to...

6 minutes read.

Boost split in C++ library

Boost::split in C++ library Boost offers strong tools for adding mature, well-tested libraries to the C++ standard library. The boost: split function, which is a component of the Boost string algorithm...

2 minutes read.

C++ Reading file

In file handling, read() function is used to read data from the file into the program. The read() uses ifstream library to read data from a file. Syntax file-stream-class   file-stream-object;   file-stream-object.read((char *)&var , sizeof (var)); <h3">Example ofstream  outfile;         outfile . read((char*)&emp,sizeof(emp)); C++ File Handling read() Function Example Reading the content of existing...

2 minutes read.

Private Inheritance in C++

Private inheritance is an inheritance in object-oriented programming (OOP) languages where a subclass derives from a superclass. Still, the derived class does not inherit the public and protected members of...

7 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

C++ this pointer

'this' is a pointer that points to the object for which this function was called. The 'this' pointer holds the memory address of the current object. The 'this' pointer is implicitly passed to...

2 minutes read.

Features of OOPS in C++

What is OOPs? The main reason programmers prefer C ++ language over C is because of the support of object-oriented programing in C++. As the name suggests, object-oriented programming or OOPs...

3 minutes read.

Reverse a Number in C++

In this tutorial, you'll learn how to utilize a C++ program to reverse a number entered by a user at runtime. Because there are various ways to write a C++...

3 minutes read.

Parameterize Constructor

C++ Parameterized Constructor A constructor having parameters is known as parameterize constructor. Parameterize constructor is used to assign different values. Syntax: className(data-type argument){   // Constructor definition   }   className(data-type argument, data-type argument){   // Constructor definition   } A parameterized constructor can be passed values to constructor function in two ways: 1)...

1 minute read.

Vector resize() in C++

Vector resize() in C++ Vectors are called dynamic arrays and can automatically adjust their size when a component is added or deleted. This container is used for storage. The function modifies the...

3 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.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

C++ Aggregation

C++ Aggregation Definition: In C++, aggregation is a process in which one class (as an entity reference) defines another class. It provides another way to reuse the class. It represents...

4 minutes read.