Passing Vector to a Function in C++
Last Updated :
11 Nov, 2024
To perform operations on vector belonging to one function inside other function, we pass this vector to the function as arguments during the function call.
C++ provides three methods to pass a vector to a function in C++. Let's look at each of them one by one.
Pass Vector by Value
The pass by value method is the simplest method to pass any vector to the function. This method will create a copy of the original vector for passing. Therefore, modifications done inside the function will not affect the original vector.
Syntax
In the function declaration, we define the argument name and type as shown:
rtype foo(vector<type> para_name);
In the function call, we just pass the vector name.
foo(vec_name);
where,
- para_name is the name that will be used in the function for referring to the copy of the vector.
- vec_name is the name of the original vector.
Example
C++
#include <bits/stdc++.h>
using namespace std;
// Pass by value
void foo(vector<int> vec) {
// Modifying vector inside function
vec.push_back(8);
for (auto i: vec) {
cout << i << " ";
}
cout << endl;
}
int main() {
vector<int> v = {1, 3, 7, 9};
// Passing the vector to foo()
foo(v);
for (auto i : v)
cout << i << " ";
return 0;
}
Explanation: The vector inside the function got one more element while the original vector remained unchanged even after the function execution.
This method is only preferred if we don't want to modify the vector, and the vector size is small because making a copy of a large vector is expensive
Pass Vector by Reference
The pass by reference method passes the reference of the vector to the function. It does not create the copy of vector therefore, all the modifications done in the function will be reflected in the original array.
Syntax
In the function declaration,
rtype foo(vector<type>& para_name);
The &
symbol indicates that the vector is passed by reference.
In the function call, we just pass the vector name.
foo(vec_name);
Example
C++
#include <bits/stdc++.h>
using namespace std;
// Pass by reference
void foo(vector<int> &vec) {
// Modifying the vector
vec.push_back(8);
for (auto i : vec)
cout << i << " ";
cout << endl;
}
int main() {
vector<int> v = {1, 3, 7, 9};
// Pass the vector to foo()
foo(v);
for (auto i : v)
cout << i << " ";
return 0;
}
Output1 3 7 9 8
1 3 7 9 8
Explanation: The function modified the original vector as we can see in the output.
Constant Vector
If we want to pass the vector to a function without modifying it, we can pass it as a constant reference using const
. This avoids unnecessary copying while ensuring the original vector remains unchanged.
Pass Vector by Pointer
The pass by pointer method is similar to the pass by reference method, but instead of a reference, we pass the memory address of the vector to the function.
Syntax
In the function declaration,
rtype foo(vector<type>* para_name);
The *
symbol indicates that the pointer to the vector.
In the function call, we just pass address of the vector.
foo(vec_name);
Example
C++
#include <bits/stdc++.h>
using namespace std;
// Pass by pointer
void foo(vector<int> *ptr) {
// Modify the original vector
ptr->push_back(8);
for (int i = 0; i < ptr->size(); i++) {
cout << ptr->at(i) << " ";
}
cout << endl;
}
int main() {
vector<int> v = {1, 3, 7, 9};
// Passing address of the vector to foo()
foo(&v);
for (auto i : v)
cout << i << " ";
return 0;
}
Output1 3 7 9 8
1 3 7 9 8
Explanation: The function modified the original vector as we can see in the output.
This method is not recommended as it brings the errors and risks associated with pointers.
Pass by Value Vs Pass by Reference Vs Pass by Pointer
Following are the differences between the pass by value, pass by reference and pass by pointer method:
Pass by Value | Pass by Reference | Pass by Pointer |
---|
This method creates a copy of vector which is passed to the function. | This method passes the reference to the original vector and does not create copy. | This method passes the address of original vector and does not create the copy of vector. |
Requires extra memory to store the copy. | No additional memory is needed. | No additional memory is needed. |
Original vector remains unchanged. | Changes will reflect in original vector. | Changes will reflect in original vector. |
Slower as compared to other methods | Fast | Fast |
No special operator is need in function declaration and call. | & operator in the function declaration specifies that the reference is being passed is a reference. | * operator in the function declaration and & operator to get the address of the vector is used in pass by pointers. |
Similar Reads
Vector in C++ STL C++ vector is a dynamic array that stores collection of elements same type in contiguous memory. It has the ability to resize itself automatically when an element is inserted or deleted.Create a VectorBefore creating a vector, we must know that a vector is defined as the std::vector class template i
7 min read
8 Ways to Initialize Vector in C++ Initializing a vector means assigning some initial values to the std::vector elements. In this article, we will learn 8 different ways to initialize a vector in C++.Table of ContentUsing Initializer ListOne by One InitializationWith a Single ValueFrom an ArrayFrom Another VectorFrom Any STL Containe
5 min read
Commonly Used Methods
Vector end() in C++ STLIn C++, the vector end() is a built-in method used to obtain an iterator pointing to the theoretical element after the last element of the vector. Even though this iterator does not point to a valid element, it serves as a marker for the end of the vector.Letâs take a look at an example that illustr
3 min read
Vector empty() in C++ STLIn C++, vector empty() is a built-in method used to check whether the given vector is empty or not. In this article, we will learn about vector empty() method in C++.Letâs take a look at an example that illustrates the vector empty() method:C++#include <bits/stdc++.h> using namespace std; int
2 min read
Vector operator[ ] in C++ STLIn C++, the vector operator [] is used to randomly access or update the elements of vector using their indexes. It is similar to the vector at() function but it doesn't check whether the given index lies in the vector or not.Letâs take a look at a simple code example:C++#include <bits/stdc++.h
3 min read
Vector front() in C++ STLIn C++, the vector front() is a built-in function used to retrieve the first element of the vector. It provides a reference to the first element, allowing you to read or modify it directly.Letâs take a quick look at a simple example that uses the vector front() method:C++#include <bits/stdc++.h
2 min read
Vector push_back() in C++ STLIn C++, the vector push_back() is a built-in method used to add a new element at the end of the vector. It automatically resizes the vector if there is not enough space to accommodate the new element.Letâs take a look at an example that illustrates the vector push_back() method:C++#include <bits/
2 min read
Vector insert() in C++ STLIn C++, the vector insert() is a built-in function used to insert new elements at the given position in a vector. In this article, we will learn about the vector insert() function in C++. Letâs take a look at an example that shows the how to use this function:C++#include <bits/stdc++.h> using
4 min read
vector emplace() in C++ STLIn C++, vector emplace() is used to insert elements at the given position in a vector by constructing it in-place within the vector, rather than creating a temporary object and then moving or copying it into the vector.Let's take a quick look at a simple example that uses vector emplace() method:C++
3 min read
Vector assign() in C++ STLIn C++, the vector assign() is a built-in method used to assign the new values to the given vector by replacing old ones. It also modifies the size of the vector according to the given number of elements. Letâs take a look at an example that shows the how to use this function.C++#include <bits/st
4 min read
Vector erase() in C++ STLIn C++, vector erase() is a built-in function that is used to delete elements from the vector. It removes an element of a specific position or range of elements from the vector. Letâs take a simple example that uses the vector erase() method:C++#include <bits/stdc++.h> using namespace std; int
3 min read
Other Member Methods
Vector max_size() in C++ STLIn C++, vector max_size() is a built-in function used to find the maximum number of elements that can be held by the vector container. In this article, we will learn about the vector max_size() function in C++.Let's take a look at an example that illustrates this method:CPP#include <bits/stdc++.h
3 min read
Vector capacity() in C++ STLIn C++, the vector capacity() is a built-in method used to find the capacity of vector. The capacity indicates how many elements the vector can hold before it needs to reallocate additional memory. In this article, we will learn about vector capacity() method in C++.Letâs take a look at an example t
3 min read
vector rbegin() and rend() Functions in C++ STLIn C++, std::vector::rbegin() and std::vector::rend() are built-in functions used to retrieve reverse iterators to the reverse beginning and reverse end of a vector. These functions allow easy traversal of vectors in reverse i.e. from the last element to the first. They are the member functions of t
3 min read
vector :: cbegin() and vector :: cend() in C++ STLVectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container. vector::cbegin() The function returns an iterator which is used to iterate container. The iterator points to the beginning of the vector.Iterat
2 min read
Vector crend() in C++ STLIn C++, the vector crend() is a built-in method used to obtain a constant reverse iterator pointing to the theoretical element just before the first element of the vector. It is used to mark the reverse end of the vector.Letâs take a look at an example: C++#include <bits/stdc++.h> using namesp
2 min read
Vector resize() in C++ STLIn C++, the vector resize() is a built-in method used to change the size of vector container after it is declared. It can be used to increase or decrease the size of vector.Letâs take a look at an example that illustrates the vector resize() method:C++#include <bits/stdc++.h> using namespace s
3 min read
Vector shrink_to_fit() in C++ STLIn C++, vector shrink_to_fit() is a built-in function used to reduce the capacity of the vector to fit its size and destroys all elements beyond the size. In this article we will learn about vector shrink_to_fit() in C++.Letâs take a quick look at an example that illustrates vector shrink_to_fit() m
2 min read
When to use Vector reserve() in C++?In a vector, when the number of elements to be inserted are greater than the current capacity, it is reallocated to a larger memory block and all the items are copied to this new block making this reallocation an expensive operation with time complexity of O(n).This mechanism works well if you don't
2 min read
Vector data() in C++ STLIn C++, the vector data() is a built-in function used to access the internal array used by the vector to store its elements. In this article, we will learn about vector data() in C++.Letâs take a look at an example that illustrates the vector data() method:C++#include <bits/stdc++.h> using nam
2 min read
2D Vector in C++ A 2D vector is a vector of the vectors i.e. each element is a vector in itself. It can be visualised as a matrix where each inner vector represents a row, and the number of rows represents the maximum columns. A 2D vector is dynamically resizable in both dimensions.SyntaxC++vector<vector<data_
7 min read
Passing Vector to a Function in C++ To perform operations on vector belonging to one function inside other function, we pass this vector to the function as arguments during the function call.C++ provides three methods to pass a vector to a function in C++. Let's look at each of them one by one.Table of ContentPass Vector by ValuePass
5 min read
How Does a Vector Internally Works in C++? In C++, a vector is a dynamic array that can resize itself when more elements are added or deleted. So, one may ask that how a vector internally works to achieve its dynamic resizing capability while maintaining similar efficiency to static arrays in operations?For vector to work as a resizable dyna
5 min read
How to implement our own Vector Class in C++? The given task is to implement a class in C++ which behaves just like the Vector class.Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements a
5 min read
Advantages of Vector Over Array in C++ In C++, both vectors and arrays are used to store collections of elements, but vector offers significant advantages over arrays in terms of flexibility, functionality, and ease of use. This article explores the benefits of using vectors in C++ programming.The major advantages of vector over arrays a
3 min read
Common Vector Programs