这个问题在这里已经有了答案:
如何在没有额外堆内存的情况下循环移位阵列? 2个答案有没有办法交换数组的两个部分而不需要创建一个新部分? 喜欢切一副纸牌? 我能够通过分配一个新数组然后插入顶部扇区然后插入下部扇区元素来实现这一点。
我已尝试在没有额外数组的情况下执行此操作,并且有两个临时变量来保存元素,而算法在各部分之间进行交换。 问题是我的尝试适用于特定情况。
例如:
原始数组:0 1 2 | 3 4 5 6 7
在指数二下跌
交换数组:
3 4 5 6 7 | 0 1 2
This question already has an answer here:
How can I cyclically shift an array without additional heap memory? 2 answersIs there a way to swap two sections of an array without needed to create a new one? Like cutting a deck of cards? I was able to do this by allocating a new array and then inserting the top sector first then the lower sector elements after.
I have made attempts to do it without the extra array and have two temporary variables to hold the elements while the algorithm does the swapping between the sections. The thing is that my attempt would work for specific cases.
For example:
original array: 0 1 2| 3 4 5 6 7
cut at index two
swapped array:
3 4 5 6 7| 0 1 2
最满意答案
您可以使用std::rotate执行此任务。 它对集合中的数据进行左旋转,因此您指定一个“剪切”点,并移动元素使得紧跟在指定剪切点之后的元素将位于开始处,而那些位于剪切点之前的元素将被移到最后。
You can use std::rotate for this task. It does a left rotate of the data in the collection, so you specify a "cut" point, and it moves the elements so the one immediately after the specified cut point will be at the beginning, and those that were before the cut point will be moved to the end.
更多推荐
发布评论