c++ - 右移数组

标签 c++ arrays

我正在生成一个随机整数数组,并尝试将值向右移动一个,并将第一个元素替换为前一个最后一个元素。

输出无序,最终元素为随机生成的整数。

#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;


   void shift(int values[], int size) {
    int temp;
    for (int i = 0; i < size; i++) {    
        temp = values[size - 1];
        values[i] = values[i + 1];
        values[0] = temp;
        cout << values[i] << setw(4);
    }
    cout << endl;
}
int main()
{
    cout << "Random 10 index array" << endl;
    const int CAP = 10;
    int numbers[CAP];

    srand(time(0));
    int i;
    for (i = 0; i < CAP; i++) {
        int rng = rand() % 100 + 1;
        numbers[i] = rng;
        cout << numbers[i] << setw(4);

    }
    cout << "shifting all elements to the right: " << endl;
shift(numbers, CAP);

    cout << endl;
    system("pause");
    return 0;
}

我尝试使用 i < size - 1 , 但我得到了我需要的 10 个数字中的 9 个。

最佳答案

你试过吗

If you want a circular shift of the elements:

std::rotate(&arr[0], &arr1, &arr[10]); ... will do the trick. You'll need to #include the algorithm header.

Optimal way to perform a shift operation on an array

编辑:如前所述,如果直接使用,std::rotate 会向左旋转。 Here是一个在 vector 上进行右旋转并进行一些更改的示例:

#include <vector>
#include <iostream>
#include <algorithm>

int main()
{
    std::vector<int> v{2, 4, 2, 0, 5, 10, 7, 3, 7, 1}; 

    // simple rotation to the right
    std::rotate(v.rbegin(), v.rbegin() + 1, v.rend());

    std::cout << "simple rotate right : ";
    for (int n: v)
        std::cout << n << ' ';
    std::cout << '\n';

}

输出:

simple rotate right : 1 2 4 2 0 5 10 7 3 7 

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

相关文章:

c++ - 编译器似乎没有使用包含

C++ Boost.Asio - tcp 套接字异步写入

c++ - 使用 pushButton 保存 QListWidget 项目

C++程序内存计算

php - Array_splice 充当 array_slice?

javascript - 来自 JSON 数组的 JQuery 中的 forEach 不是函数错误

c++ - 错误 : "2 overloads have similar conversions"

C++ 二维动态数组分配

java - 如何在运算符处拆分字符串

c++ - 如何测试unsigned char数组的结尾?