I am trying to implement insert function using std::move_backward. I found this code on cplusplus.com. I don't quite understand how std::move_backward work.
#include <algorithm> // std::move_backward
#include <string> // std::string
int main () {
std::string elems[10] = {"air","water","fire","earth"};
// insert new element at the beginning:
std::move_backward (elems,elems+4,elems+5);
elems[0]="ether";
std::cout << "elems contains:";
for (int i=0; i<10; ++i)
std::cout << " [" << elems[i] << "]";
std::cout << '\n';
return 0;
}
output is "elems contains: [ether] [air] [water] [fire] [earth] [] [] [] [] []"
how would you insert into 2nd position(or any position) using the same method as above such that
the output would be
output: elems contains: [air] [ether] [water] [fire] [earth] [] [] [] [] []
If you want to insert ether
into the second position, simply change the range that you are moving backwards to not include the 0th position:
std::move_backward(elems+1, elems+4, elems+5);
// ^^ ignore 0th position
elems[1]="ether"; // insert element at at 1st position
Here's a demo