Getting slice or a sub-vector from a vector in C++
Hello Coders! In this tutorial, we will be going to learn how we can get a sub-vector or a slice from a vector in C++.
Getting a slice from a vector means we are trying to get a sub-vector or a small part from our original vector.
C++ Code: Sub-vector from a vector in C++
Lets Code It:—>
#include <iostream> #include<vector> //include vector header file using namespace std; template<typename T> //using templates here vector<T>vec(vector<T> const &p, int x, int y) { auto first = p.begin() + x; auto last = p.begin() + y + 1; vector<T> vector(first, last); return vector; } template<typename T> void show(vector<T> const &p) { for (auto i: p) { cout << i << ' '; } } int main() { vector<int> p = {100,200,300,400,500,600,700,800,900,1000}; //insert vector elements int j = 3; //starting index int k = 8; //ending index cout<<"Our resulting sub-vector would be:"<<"\n"; //print this statement vector<int> sub_vector = vec(p, j, k); show(sub_vector); //display output }
Output:
Our resulting sub-vector would be: 400 500 600 700 800 900
Code Discussion:
First, we will be going to declare vec as our vector and then we will be going to initialize the start and end point of our vector using our constructor auto first and auto end.
After that our variable of vector type will be declared and we will be going to pass our first and last element into that return our vector. Then template and show function would be declared and we will pass the constructor as our parameters.
Declare a vector p and insert the elements and then we will initialize the value of our j and k as starting and ending point of the vector’s indexes we will be taking out from our original vector. Using cout statement our sub -vector will be printed and then we will initialize the values for sub-vector vec(p,j,k) and where j and k represents start and end indexes respectively.
In the end, our show function will be called so that our sub-vector will be displayed on our output screen.
Note: Don’t forget to use vector header file .
Leave a Reply