How to return null vector in C++

Hello folks! In this tutorial, we are going to learn how we can return a null vector in C++. Before going deep into the topic let’s understand what are null vectors.

Null Vectors

Null vectors are usually defined as vectors that do not have any storage container ie . an empty storage container. But practically there is no such term as a null vector but we can return a null vector in C++.

C++ Code: How to return null vector in C++

Let’s understand this using a code as an example:-

#include <iostream>
#include <vector>

using std::cout;
using std::vector;

vector<int> retvec(vector<int> &var1)
{
    return vector<int>();
}

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

    var2 = retvec(var1);
    return 0;
}

Output:


Explanation to the Code:

Include necessary header files. Declare using std::cout and std::vector. Declare function with vector type return type which accepts vector as a variable.  Then return null vector inside function body. Declare main function. Declare vector and assign values to it. Declare another variable. Call the function.  Write return type of main function.

Leave a Reply

Your email address will not be published.