Open In App

How to Extract a Subvector from a Vector in C++?

In C++, vectors are dynamic arrays that can grow and reduce in size as per requirements. In this article, we will learn how to extract a subvector from a vector in C++.

Input:
main_vector = {10, 20, 30, 40, 50, 60}
start = 2
end = 5

Output:
subvector: {30, 40, 50}

Getting a Subvector from a Vector in C++

To extract a subvector from a std::vector in C++, we can use the std::vector's ranged constructor that takes two iterators as arguments to specify the start and end positions of the range within the original vector that we want to copy to the subvector.

Approach

C++ Program to Extract a Subvector from a Vector

The below program demonstrates how we can extract subvector from a vector in C++.

// C++ program to illustrate how to extract a subvector from
// a vector
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    // Main vector
    vector<int> main_vector = { 10, 20, 30, 40, 50, 60 };

    // Start and end indices of the subvector
    int start = 2, end = 5;

    // Extract subvector
    vector<int> sub_vector(main_vector.begin() + start,
                           main_vector.begin() + end);

    // Print the subvector
    cout << "Subvector: ";
    for (int i = 0; i < sub_vector.size(); i++)
        cout << sub_vector[i] << " ";
    cout << endl;

    return 0;
}

Output
Subvector: 30 40 50 

Time Complexity: O(N), here N is the size of the vector.
Auxiliary Space: O(N)



Article Tags :