[英]Shifting elements in array C++
Im wondering why my data in 'intFront' does not stay the same. 我想知道为什么我在'intFront'中的数据不会保持不变。 Im shifting the elements in my array left:
我将数组中的元素向左移动:
void stack::rotate(int nRotations)
{
for (; nRotations > 0 ;) // Number of Rotations to the left
{
intFront = &items[top+1].n;
for ( int shiftL = 0; shiftL < count-1; shiftL++ )
{
items[shiftL] = items[shiftL+1]; // shift left from the front
}
items[count-1].n = *intFront;
nRotations--; // decrement=0 will indicate no more rotations left
}
}
Whats happening is that the first value or "head" or "front" of the array is put into a varaible 'intFront'. 发生的是将数组的第一个值或“ head”或“ front”放入可变的“ intFront”中。 I rotate everything left by the given number of rotations, hoping to just make a simple transfer at the end.
我旋转给定旋转次数剩下的所有内容,希望最后做一个简单的转移。 Guess not..
可能不会..
items[shiftL+1]
goes beyond array bounds at last iteration, items[shiftL+1]
读取超出了数组的范围, intFront
and then override these structures by value in the inner loop - that'll sure change value intFront
points to, intFront
,然后在内部循环中按值覆盖这些结构-这将确保将intFront
指向的值intFront
为 nRotations
). nRotations
)。 You're storing a pointer to a memory address, not the value itself. 您存储的是指向内存地址的指针,而不是值本身。 Thus when you shift things around in the array, what used to be in that memory address is overwritten, but the memory address is still constant.
因此,当您在数组中移动数据时,该内存地址中的内容将被覆盖,但内存地址仍保持不变。 What you really want to be doing is storing the value of items[top+1].n (w/o the & in front) and then reassign it (without the * for dereferencing).
您真正想做的是存储items [top + 1] .n(不带&开头)的值,然后重新分配它(不带*表示取消引用)。
void stack::rotate(int nRotations)
{
for (; nRotations > 0 ;) // Number of Rotations to the left
{
intFront = items[top+1].n;
for ( int shiftL = 0; shiftL < count-2; shiftL++ )
{
items[shiftL] = items[shiftL+1]; // shift left from the front
}
items[count-1].n = intFront;
nRotations--; // decrement=0 will indicate no more rotations left
}
}
Nikolai's tips are good as well - you don't really need to do this in two nested loops (which is O(N^2) ); Nikolai的技巧也很好-您实际上不需要在两个嵌套循环( O(N ^ 2) )中执行此操作; you could do it with just a single loop (or two sequential loops for simplicity) which would be O(N) time.
您可以只用一个循环(或为简单起见两个连续循环)来完成,这将是O(N)时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.