c++ - 数组转移到下一个元素

标签 c++ arrays

如何将数组中的元素移动到下一个元素

eg: x[5] = { 5, 4, 3, 2, 1 }; // initial values
    x[0] = 6; // new values to be shifted
    x[5] = { 6, 5, 4, 3, 2 }; // shifted array, it need to be shifted, 
                              // not just increment the values.

这是我目前所做的。这是错误的,这就是我在这里需要帮助的原因。提前致谢。

#include <iostream>

using namespace std;

int main() 
{
  int x[5] = { 5, 4, 3, 2, 1 };

  int array_size = sizeof(x) / sizeof(x[0]);

  x[0] = 6;

  int m = 1;

  for(int j = 0; j < array_size; j++) {
    x[m+j] = x[j];
    cout << x[j] << endl;
  }

  return 0;
}

最佳答案

#include<algorithm>

// ...
std::rotate(x, x+4, x+5);
x[0] = 6;

关于c++ - 数组转移到下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3650372/

相关文章:

c++ - "Python Exception <class ' gdb.error '> There is no member named _M_dataplus."尝试打印字符串时

javascript - 选择两个单词之间的单词

java - 如何找到数组中元素的索引?

c++ - Eclipse CDT - OSX 上没有控制台输出

c++ - NITE2::UserTracker 在读取 oni 文件时崩溃

c++ - 从 vector 中删除最后一个元素会导致迭代出现问题

Javascript - 如何在某个索引处启动 forEach 循环

java - 在 Java 中使用正则表达式复制数组

c# - 你如何遍历多维数组?

c++ - 如何将 asmjit 嵌入到自己的 C++ 项目中?