- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想按 Rust 中的预定义顺序就地对 Vec
进行排序(重新排序)。
例如:
let i = vec![0, 3, 2, 1];
let mut v = vec!["a", "b", "c", "d"];
v.sort_by_indices(&i);
assert_eq!(v, &["a", "d", "c", "b"]);
我想就地执行此操作。在我的用例中,v
占用大量内存。
最佳答案
就地实现很棘手,但可以在 O(n) 时间内实现。它通过追踪索引和交换元素来工作,直到它回到它开始的地方。不幸的是,这确实需要暂存空间来跟踪哪些元素已经排序。这是一个在允许使用索引数组的情况下重用索引数组的实现:
fn sort_by_indices<T>(data: &mut [T], mut indices: Vec<usize>) {
for idx in 0..data.len() {
if indices[idx] != idx {
let mut current_idx = idx;
loop {
let target_idx = indices[current_idx];
indices[current_idx] = current_idx;
if indices[target_idx] == target_idx {
break;
}
data.swap(current_idx, target_idx);
current_idx = target_idx;
}
}
}
}
查看它在 playground 上的工作(@Jmb 进行了改进)。
否则您需要为暂存空间单独分配(可能是 BitVec
)。如果此方法可行而无需跟踪已排序的元素,请随意评论或编辑。
关于sorting - 如何按索引对 Vec 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69764803/
假设我有一个组织 ID 向量 let orgs = vec![1, 3, 14, 12]; 然后我调用 .iter()在 each 上获取每个组织的事件,其中函数 get_events_for()返回
这个问题已经有答案了: What are Rust's exact auto-dereferencing rules? (4 个回答) 已关闭 3 年前。 我很困惑为什么这个函数 get适用于 Vec
let a = vec![ vec![1, 2], vec![3, 4], vec![5, 6] ]; 怎么才能聚成一个Vec包含在所有 Vec 中的所有值s 在 a ? 最佳答案 您可以使用 fla
我在HashMap, Vec>中有数据,我想将该数据作为字节缓冲区(单个Vec)写入文件,然后从文件中读取回去并重建HashMap结构。 是否有建立像这样的平坦化和恢复 map 的算法?我可以将元数据
我正在寻找一种“使用rust ”的方式来将 Vec 累积到 Vec 中,以便将每个内部 Vec 的第一个元素加在一起,将每个 Vec 的每个第二个元素加在一起,等等......,并将结果收集到 Vec
我正在寻找一种“使用rust ”的方式来将 Vec 累积到 Vec 中,以便将每个内部 Vec 的第一个元素加在一起,将每个 Vec 的每个第二个元素加在一起,等等......,并将结果收集到 Vec
我正在尝试使用 selection_sort 创建一个已排序的向量,同时保留原始未排序的向量: fn main() { let vector_1: Vec = vec![15, 23, 4,
在 https://doc.rust-lang.org/std/vec/struct.Vec.html#method.iter , 我只能在页面左侧的索引侧边栏中找到iter。但是,找不到 iter_
我正在尝试从 Vec> 创建一个集合向量 ( Vec> ) .这是我目前的进展: use std::collections::BTreeSet; fn main() { // The data
我错过了向量向量初始化的一些东西。在第一种方法中,我尝试了这段代码: let mut landFirst: Vec> = Vec::with_capacity(width); for v in lan
我想设计一个类似于示例 here 的函数除了我的情况,iproduct 的参数数量在编译时是未知的。正如 here 所解释的那样,这在 python 中很容易完成。 . 我已经尝试使用 itertoo
我有一个我不明白的问题: fn cipher_with(key: &[u8], data: &[u8]) -> Vec { let data_len = 16; let mut dat
我刚开始学习 Rust,我偶然发现了这个愚蠢的问题: error: mismatched types: expected `&[u8]` but found `&collections::vec::V
这个问题在这里已经有了答案: How to filter a vector of custom structs? (1 个回答) 关闭 4 年前。 我有一个接受 &Vec 的函数(其中 Word 是
试图创建一个 HashMap 的数据库结构向量。每个Vec包含 Box . use std::collections::HashMap; trait Model { fn id(&self)
我正在编写一个使用 Vec> 的库类型以按列优先顺序存储数据(每个内部 Vec 代表一列)。用户可以创建 Vec>具有任何行和列长度,但所有列都被限制为相同的长度。 有时我需要高效地遍历 Vec>按行
在 GLSL 中我不明白什么是“in”和“out”变量,这是什么意思?这是我从教程中复制的代码示例。 // Shader sources const GLchar* vertexSource =
例如 [[5,6][2,3][2,5][2,9][1,6]]先按第一个元素升序排序,当一个元素相等时,按第二个元素降序排序,得到[1,6],[2,9],[2,5],[2,3] ],[5,6] 最佳答案
我正在尝试为类型为Vec>的向量创建可变的迭代器 迭代器代码: pub struct IterMut { iter: &'a mut Vec>, ix: usize, inne
我是 rust 编程的新手。我想用递归实现合并排序。这是我的代码: fn merge(a: &mut Vec, b: &mut Vec) -> Vec { let mut temp: Vec
我是一名优秀的程序员,十分优秀!