Pre-requisite: Vectors in C++
Slicing a vector means to make a subvector from a given vector.
Given N integers in a vector arr and to positive numbers X and Y, the task is to slice the given vector from index X to Y in a given vector.
Examples:
Input: vector arr = { 1, 3, 4, 2, 4, 2, 1 }, X = 2, Y = 5
Output: 4 2 4 2
Input: vector arr = { 1, 3, 4, 2 }, X = 1, Y = 2
Output: 3 4
Method 1: The idea is to copy the elements from this range X to Y to a new vector and return it.
- Get the starting iterator of element at index X as:
auto start = arr.begin() + X
-
- Get the ending iterator of element at index Y as:
auto end = arr.begin() + Y + 1
-
- Copy the elements in these range between these iterators using copy() function in vector.
Below is the implementation of the above approach:
CPP
#include "bits/stdc++.h"
using namespace std;
vector< int > slicing(vector< int >& arr,
int X, int Y)
{
auto start = arr.begin() + X;
auto end = arr.begin() + Y + 1;
vector< int > result(Y - X + 1);
copy(start, end, result.begin());
return result;
}
void printResult(vector< int >& ans)
{
for ( auto & it : ans) {
cout << it << ' ' ;
}
}
int main()
{
vector< int > arr = { 1, 3, 4, 2,
4, 2, 1 };
int X = 2, Y = 5;
vector< int > ans;
ans = slicing(arr, X, Y);
printResult(ans);
}
|
Method 2: The above approach can be implemented using Range Constructor. Below is the implementation of the above approach:
CPP
#include "bits/stdc++.h"
using namespace std;
template < typename T>
vector<T> slicing(vector<T> const & v,
int X, int Y)
{
auto first = v.begin() + X;
auto last = v.begin() + Y + 1;
vector<T> vector(first, last);
return vector;
}
template < typename T>
void printResult(vector<T> const & v)
{
for ( auto i : v) {
cout << i << ' ' ;
}
cout << '\n' ;
}
int main()
{
vector< int > arr = { 1, 3, 4, 2,
4, 2, 1 };
int X = 2, Y = 5;
vector< int > ans;
ans = slicing(arr, X, Y);
printResult(ans);
}
|
Method 3: We can also use inbuilt function slice() in C++ STL to slice the given vector. Below is the implementation of the above approach:
CPP
#include "bits/stdc++.h"
#include "valarray"
using namespace std;
valarray< int > slicing(valarray< int > arr,
int X, int Y)
{
return arr[slice(X, Y - X + 1, 1)];
}
void printResult(valarray< int > v)
{
for ( auto i : v) {
cout << i << ' ' ;
}
cout << '\n' ;
}
int main()
{
valarray< int > arr = { 1, 3, 4, 2,
4, 2, 1 };
int X = 2, Y = 5;
valarray< int > ans;
ans = slicing(arr, X, Y);
printResult(ans);
}
|
Last Updated :
02 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...