如何习惯性地迭代数组的一半并修改另一数组的结构? [英] How to idiomatically iterate one half of an array and modify the structure of the other?

查看:34
本文介绍了如何习惯性地迭代数组的一半并修改另一数组的结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在向量的前半部分进行迭代(读取)并根据前半部分更改向量后半部分的结构的惯用方式是什么?这是非常抽象的,但是一些算法可以归结为这个问题.我想在Rust中编写这个简化的C ++示例:

What is the idiomatic way to iterate (read) over the first half of the vector and change the structure of the second half of the vector depending on the first? This is very abstract but some algorithms could be boiled down to this problem. I want to write this simplified C++ example in Rust:

for (var i = 0; i < vec.length; i++) {
    for (var j = i + 1 ; j < vec.length; j++) {
        if (f(vec[i], vec[j])) {
            vec.splice(j, 1);
            j--;
        }
    }
}

推荐答案

Rust和C对于此通用问题的惯用解决方案是相同的,因为没有任何允许简化的约束.

An idiomatic solution of this generic problem will be the same for Rust and C, as there's no constraints which would allow simplification.

我们需要使用索引,因为向量重新分配将使迭代器包含的引用无效.我们需要在每个循环上将索引与向量的当前长度进行比较,因为长度可以更改.因此,惯用的解决方案将如下所示:

We need to use indexes because vector reallocation will invalidate the references contained by the iterators. We need to compare the index against the current length of the vector on each cycle because the length could be changed. Thus an idiomatic solution will look like this:

let mut i = 0;
while i < v.len() {
    let mut j = i + 1;
    while j < v.len() {
        if f(v[i], v[j]) {
            v.splice(j, 1);
        } else {
            j += 1;
        }
    }
    i += 1;
}

游乐场链接

尽管此代码涵盖了一般情况,但很少有用.它没有捕获细节,而这些细节通常是手头问题所固有的.反过来,编译器无法在编译时捕获任何错误.我不建议在不首先考虑其他方法的情况下编写此类内容.

While this code covers the general case, it is rarely useful. It doesn't capture specifics, which are usually inherent to the problem at hand. In turn, the compiler is unable to catch any errors at compile time. I don't advise writing something like this without considering another approaches first.

这篇关于如何习惯性地迭代数组的一半并修改另一数组的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆