This tutorial will discuss about a unique way to return an array from a function in C++.
We can return only a single value from a function. But to return an array from a function, we need to return two values i.e.
- An integer pointer, pointing to the start of array.
- The size of array.
We can create a pair
of int pointer
and size_t
to store this information, and return that pair
from the function. The one who is calling the function can fetch the integer pointer and size of array from the pair
and use them to access array elements.
Let’s see a function that creates an int array on heap, and initializes that array with incemental values. Then it creates a pair of,
int *
, pointing to the start of array- size of array
// Creates an int array of size 10 dynamically // and returns a pair of int * , & size of array std::pair<int *, size_t> getData() { size_t len = 10; // Create a dynamic int array of size 10 int* arr = new int[len]; // Initialize the value sof array for (int i = 0; i < len; i++) { arr[i] = i; } // Return a pair of an int pointer pointing to array // and size of array return std::make_pair(arr, len); }
We need to include the header file <utility>
to use the std::pair
and std::make_pair()
. Then we can call this function to get the array details from the returned pair,
// Get an array from a function std::pair<int *, size_t> result = getData(); // Fetch first element of pair i.e. int pointer int * arr = result.first; // Fetch second element of pair i.e. size size_t len = result.second;
Let’s see the complete example, where will fetch an array from a function and the interate over that array to print its contents.
Let’s see the complete example,
#include <iostream> #include <utility> // Creates an int array of size 10 dynamically // and returns a pair of int * , & size of array std::pair<int *, size_t> getData() { size_t len = 10; // Create a dynamic int array of size 10 int* arr = new int[len]; // Initialize the value sof array for (int i = 0; i < len; i++) { arr[i] = i; } // Return a pair of an int pointer pointing to array // and size of array return std::make_pair(arr, len); } int main() { // Get an array from a function std::pair<int *, size_t> result = getData(); // Fetch first element of pair i.e. int pointer int * arr = result.first; // Fetch second element of pair i.e. size size_t len = result.second; // Iterate over array and print its contents for (int i = 0; i < len; i++) { std::cout<< arr[i] << ", "; } std::cout << std::endl; // Free the memory allocated on heap delete[] arr; return 0; }
Output :
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
Summary
Today we learned about several ways to how to return an array from a function in C++. Thanks.