C ++数组“剪切”算法[重复](C++ Array “Cut” Algorithm [duplicate])

编程入门 行业动态 更新时间:2024-10-26 08:34:08
C ++数组“剪切”算法[重复](C++ Array “Cut” Algorithm [duplicate])

这个问题在这里已经有了答案:

如何在没有额外堆内存的情况下循环移位阵列? 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 answers

Is 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.

enter image description here

更多推荐

本文发布于:2023-08-01 19:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1364805.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   算法   Array   duplicate   Algorithm

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!