How can we shift array members one position?
For example, if we have n sized array with one empty element, and we shift all elements to right of a member pos by one position, we can copy n-1th member into the empty element, and so on.
code:
#include <iostream>
using namespace std;
// we take the position of insertion, then right shift all elements
// then insert the required number
int main() {
int n = 10;
int list[n];
cout << "Enter " << n-1 << " elements:\n";
for( int i = 0; i < n-1; ++i) {
cin >> list[i];
}
int pos, num;
cout << "Position ( start: 1 ): ";
cin >> pos;
if( pos < n && pos >= 0 ) {
cout << "No. to be inserted: ";
cin >> num;
for( int i = n-2; i >= pos-1; --i) {
list[i+1] = list[i];
}
list[pos-1] = num;
for( int i = 0; i < n; ++i) {
cout << list[i] << ' ';
}
return 0;
}
}
But can we not, by some means, shift the whole sub-array in one go, sliding all members right by one?
Also can we implement this with vectors? And will vectors be more efficient or better way to achieve this?