loops - 比较列表中的所有元素并获取匹配对的可变引用
问题描述
我的目标是根据某些标准将列表中的每个元素与列表中的每个其他元素进行比较。在伪代码中,类似于:
for i, x in list.enumerate():
for y in list[i..]:
if x.match(y):
// Modify both x and y
我想获得对每个匹配对中两个项目的可变引用。这被证明是困难的。根据这个答案,获得对列表中多个项目的可变引用的最佳方法是通过split_at_mut。我编写了一个包装函数来提取两个对列表的可变引用:
/// Gets two mutable references to elements i and j in list
fn get_pair<'a, T>(i: usize, j: usize, list: &'a mut [T]) -> (&'a mut T, &'a mut T) {
let (a, b) = list.split_at_mut(j);
let first = &mut a[i];
let second = &mut b[0];
(first, second)
}
但是,如果不违反借用规则,我仍然无法在嵌套的 for 循环中使用此函数:
for stuff1 in list.iter() {
// immutable borrow on list here
for stuff2 in list[i..].iter() {
if stuff1.compare(stuff2) {
let (stuff1, stuff2) = get_pair(i, j, list); // mutable borrow on list
do_something(stuff1, stuff2);
}
}
}
相反,我保存了一对匹配的索引,然后在不同的循环中实际获取元素并对其进行处理。
// Find matching pairs and push their indices
let mut matches: Vec<(usize, usize)> = Vec::new();
for (i, stuff1) in list.iter().enumerate() {
for (j, stuff2) in list[i..].iter().enumerate() {
if stuff1.compare(stuff2) {
matches.push((i, j));
}
}
}
// Get two mutable references by indices from list
for m in matches.iter() {
let (i, j) = m;
let (stuff1, stuff2) = get_pair(*i, *j, list);
do_something(stuff1, stuff2);
}
这可行,但似乎有点过于复杂。有没有更简单或更简单的方法可以在不违反借用规则的情况下实现这一目标?
理想情况下,我想修改原始循环中的匹配对,而不需要单独的循环来遍历索引。
可以在操场上找到我当前代码的完整示例。
解决方案
你可以这样做,它会生成相当不错的代码:
let mut list = [1, 2, 3];
for i in 0..list.len() {
let (a, b) = list.split_at_mut(i);
let item_b = &mut b[0];
for item_a in a {
println!("{} {}", item_a, item_b);
}
}
这里的关键是0..len
迭代避免将 锁定list
为只读。split_at_mut
向借用检查器证明两个引用不能指向同一个元素。
推荐阅读
- javascript - 如何根据 url ID 映射元素?
- swift - Swift 中基于 XML 的自定义文档
- curl - Unable to read resources via K8s API
- c# - 出现表单错误时不显示 ASP.NET MVC 验证摘要
- dart - 对函数参数使用扩展运算符
- reactjs - NextJS - 经过身份验证和未经身份验证的用户的静态页面
- java - 运行“java”时出错:在 android studio 中找不到默认活动
- css - Material UI 中的 GridListTile 项目未对齐
- c# - 具有已知指纹的 Renci.SshNet 预接受密钥
- java - CAS的高可用配置