Return a Vector from a Function in C++

In this article, we are going to learn how to return a Vector from a function in C++. We often work on a Vector inside a function and then we need to return this Vector to the calling function. In this post, we will learn different ways of how to return a Vector from a function to its calling function.

How to return a Vector from a function in C++


  • How to pass a Vector to a function as an argument.
  • How to return a vector from a function in C++

1. How to pass a Vector to a function as an argument


So we will create a vector and we will pass this vector to a function and this function will add 2 to each of the vector elements, also it will add a new element 100 to this vector. After all this, we will return this vector to the calling function so we can see the modified vector is received there. Let us jump to our program.

#include <iostream>
#include <vector>

using namespace std;

vector<int> ModifyVector(const vector<int> *arr)
{
    vector<int> tmp{};

    for (const auto &item : *arr) {
        tmp.push_back(item + 2);
    }
	
	tmp.push_back(100);
    return tmp;
}

int main()
{
    vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    vector<int> vecAdd = ModifyVector(&vec);

    cout << "The Modified Vector Received is : ";
	
    for (int i : vecAdd) 
	{
        cout << i << ", ";
    }
    
    return 0;
}

Output

The Modified Vector Received is : 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 100,

2. How to return a string vector from a function


#include <iostream>
#include <vector>

using namespace std;

vector<string> ModifyVector(const vector<string> *arr)
{
    vector<string> tmp{};

    for (const auto &item : *arr) {
        tmp.push_back(item);
    }
	
	tmp.push_back("Dhoni");
    return tmp;
}

int main(){
    vector<string> vec = {"sachin","Dravid", "Sourav"};

    vector<string> vecAdd = ModifyVector(&vec);

    cout << "The Modified Vector Received is : ";
	
    for (string i : vecAdd) 
	{
        cout << i << ", ";
    }
    
    return 0;
}

Output

The Modified Vector Received is : sachin, Dravid, Sourav, Dhoni,