rust 如何从std::cmp::Reverse::[已关闭]获取T值< T>

hs1rzwqc  于 2022-12-19  发布在  其他
关注(0)|答案(2)|浏览(139)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
9天前关闭。
Improve this question
我在Rust中有一个i32的最小堆,我想计算它的元素之和并将其存储在i32中。

let mut total_sum = 0;
for current in min_heap {
    total_sum = current + total_sum;
}

编译时出现以下错误:

cannot add `{integer}` to `Reverse<i32>`
sqougxex

sqougxex1#

在将堆内部的Reverse<i32>Map到它们的内部值之后,可以简单地在迭代器上调用sum方法。

let total_sum: i32 = min_heap.into_iter()
                            .map(|i| i.0)
                            .sum();

一些建议:
1.避免突变;
1.不要使用x = x + y,而使用x += y;
1.不要在函数和变量名中使用camelCase;
1.不要使用换行符大括号。

mspsb9vt

mspsb9vt2#

可以使用元组访问器.0,也可以使用解构。

let mut total_sum = 0;
for current in min_heap {
    total_sum += current.0;
}

或伴随着解构:

let mut total_sum = 0;
for Reverse(current) in min_heap {
    total_sum += current;
}

相关问题