c++ - 如何使用 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] [] [] [] [] []
解决方案
如果要插入ether
第二个位置,只需将向后移动的范围更改为不包括第 0 个位置:
std::move_backward(elems+1, elems+4, elems+5);
// ^^ ignore 0th position
elems[1]="ether"; // insert element at at 1st position
这是一个演示
推荐阅读
- string - Powershell Sting 操作
- javascript - Javascript计时器已经在运行,只有在刷新时间重复时,如何防止时间重复
- java - 如何验证文件是否已创建并获取文件内容?
- c# - 如何解决我的项目依赖问题?
- mongodb - 从主机连接到访客 VM 中的 mongodb
- .net - 在 Visual Studio 构建后事件中获取 .NET 目标平台
- gcc - 要求 gcc 打印没有 dir 的错误位置,只打印文件名
- c++ - 学习使用 pthread,调用函数 master_Level() 时将 pthread 作为参数传递的正确语法是什么?
- kubernetes - Harbor 多版本映像
- python - 使用多处理对 python+sqlalchemy sqlite 数据库的并发写访问