我想要对VecDeque进行排序或倒排.在Rust 1.48.0或更高版本中,您可以使用make_contiguous()可变地访问底层片来执行以下操作:

v.make_contiguous().reverse(); //reverse
v.make_contiguous().sort(); //sort

然而,我不得不在竞争性编程中使用Rust 1.42.0.unsafe是允许的.夜间Rust 是不允许的.

我不想先将VecDeque收集到Vec中,然后反转或排序结果,最后将Vec收集回VecDeque,这似乎不必要地非常缓慢和冗长.

有没有更优雅的方式?

推荐答案

as_mut_slicesrotate_right加起来.

fn sort_vecdeque<T: Ord>(x: &mut VecDeque<T>) {
    x.rotate_right(x.as_slices().1.len());
    assert!(x.as_slices().1.is_empty());
    x.as_mut_slices().0.sort();
}

这是因为VecDeque等于implemented:这是一个单一的内存分配,在结尾和开始(如果是head > tail)或中间(如果是head < tail)都有空洞.

  • 如果孔位于起点和终点,则元素已经是连续的.
  • If the hole is in the middle, the front of the deque is at the end of the allocation, and the back of the deque is at the beginning of the allocation. rotate_right "pops the last k items and pushes them to the front.", i.e. it removes the elements at the start of the allocation and adds them to the elements at the back of the allocation, so the deque will be contiguous.
    (The way I read the docs, there's not really a guarantee that it will always be that way, which is why I like having the assert there.)

最后,如果二人组是连续的, as_slice(和它的mut个朋友) 将返回两个切片,但第二个切片将为空,所有元素都在第一个切片中.

此外,使用SO进行编码比赛可能会被认为是作弊.

Rust相关问答推荐

Rust中的相互递归特性与默认实现

铁 rust 干线无法使用PowerShell获取环境变量

当T不执行Copy时,如何返回Arc Mutex T后面的值?

如何模拟/创建ReqData以测试Actix Web请求处理程序?

重写Rust中的方法以使用`&;mut self`而不是`mut self`

如何迭代属性以判断相等性?

返回Result<;(),框<;dyn错误>>;工作

Rust 中什么时候可以返回函数生成的字符串切片&str?

为什么 tokio 在以奇怪的方式调用时只运行 n 个任务中的 n-1 个?

期望一个具有固定大小 x 元素的数组,找到一个具有 y 元素的数组

为什么特征默认没有调整大小?

write_buffer 不写入缓冲区而是输出零 WGPU

Rust 中指向自身的引用如何工作?

中文优化标题:跳出特定循环并返回一个值

部署Rust发布二进制文件的先决条件

缺失serde的字段无法设置为默认值

Rust 程序中的内存泄漏

Rust:`sort_by` 多个条件,冗长的模式匹配

有没有办法隐藏类型定义?

如何构建包含本地依赖项的 docker 镜像?