首页 > 解决方案 > 如何使用 std::move_backwards 插入给定位置的数组

问题描述

我正在尝试使用 std::move_backward 实现插入功能。我在 cplusplus.com 上找到了这段代码。我不太明白 std::move_backward 是如何工作的。

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

您将如何使用与上述相同的方法插入第二个位置(或任何位置),以便输出为 output: elems contains: [air] [ether] [water] [fire] [earth] [] [] [] [] []

标签: c++c++11stdmove

解决方案


如果要插入ether第二个位置,只需将向后移动的范围更改为不包括第 0 个位置:

std::move_backward(elems+1, elems+4, elems+5);
                    //  ^^ ignore 0th position
elems[1]="ether"; // insert element at at 1st position

这是一个演示


推荐阅读