2016-11-22 95 views
0

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

输出没有排序,最后一个元素是一个随机生成的整数。

#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,但是我得到了9个我需要的10个数字。

+1

[你的橡皮鸭子想和你谈谈](https://en.wikipedia.org/wiki/Rubber_duck_debugging)。根据你的橡皮鸭,你的阵列的最后一个元素应该移动到第一个元素一次,作为这个旋转的一部分。这是不言而喻的,你的橡皮鸭想知道你期望如何工作,何时这样做的代码将在每次循环迭代中执行,而不仅仅是一次。看起来,你的代码对你的橡皮鸭根本没有任何意义。 –

+0

我错过了什么,呼叫转移的地方。 – IronMan007

+0

'std :: deque'是比这个应用程序更好的选择。 –

回答

1

这里是有问题的代码:

 temp = values[size - 1]; 

这种说法不使用循环变量。它为什么坐在循环中?这项任务将继续发生size-1次。

 values[i] = values[i + 1]; 

你的循环不变为i <size,但您尝试访问i+1。这只是要求麻烦:)。这就是为什么当你使用i < size-1时你不会得到垃圾值。

 values[0] = temp; 

此外,这不使用循环变量。它不属于循环。你只需一遍又一遍地保持设置values[0]

这里有这样的作品,使用两个临时变量的解决方案:

void shift(int values[], int size) { 
    7  int temp = values[size-1], temp1; 
    8  for (int i = 0; i < size; i++) { 
    9   temp1 = values[i]; 
10   values[i] = temp; 
11   temp = temp1; 
12   cout << values[i] << setw(4); 
13  } 
14  cout << endl; 
15 } 
+0

我很感谢帮助,更多的解释。 – Ozymandias

0

你尝试

如果希望元素的循环移位:

的std ::旋转(& ARR [0],& ARR 1,& ARR [10]); ......会做的。你需要#包括算法头文件# 。

Optimal way to perform a shift operation on an array

编辑:正如指出的那样,性病::旋转。如果直接使用向左旋转。 Here是例如在向量做右移了一些变化:

#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 
+0

恐怕旋转功能只能将东西旋转到左边。 – Ozymandias

+0

更新了答案 – maz