mercredi 2 décembre 2020

How to insert into an array given a position using std::move_backwards

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] [] [] [] [] []

Aucun commentaire:

Enregistrer un commentaire