Open In App

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

Last Updated : 19 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • First, determine the start and end indices of the subvector.
  • Use std::vector::begin() function to get the iterator to the first element of the original vector.
  • Add the start and end indices to these iterators to get the range of the subvector.
  • Finally, use the range constructor of std::vector to create a new subvector by specifying the starting and ending iterators of the range.

C++ Program to Extract a Subvector from a Vector

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

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)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads