I am actually trying to solve the K rotate question where we have to rotate the key number of elements to the right and place them on the left. I have checked the whole code using a normal array instead of a vector and it works fine but the function with the vector array never returns anything when i run this. I have checked all the online resources and cannot identify what exactly is the error as the logic and syntax are both correct. pls, help out with this !!
#include<bits/stdc++.h>
using namespace std;
vector<int> rotate_array(vector<int> arr, int n, int key)
{
int i,j=0;
vector<int> subst;
for(i=n-1; i>=n-key; i--)
{
subst[j] = arr[i];
j++;
}
j=0;
for(i=key; i<n; i++)
{
subst[i] = arr[j];
j++;
}
return subst;
}
int main()
{
vector<int> arr = {1, 2, 3, 4, 5};
// output for this should be -- {4, 5, 1, 2, 3}
int n = arr.size();
int key = 2;
vector<int> array = rotate_array(arr, n, key);
for(int i=0; i<n; i++)
{
cout<<array[i]<<" ";
}
}
std::rotate()exists.