rust - 如何从 std::cmp::Reverse::<T> 获取 T 值

标签 rust types reverse min-heap

我有一个最小堆 i32在 Rust 中,我想计算其元素的总和并将其存储在 i32 中.

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

编译时出现以下错误:

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

最佳答案

您只需调用sum即可映射后迭代器上的方法 Reverse<i32>位于你的堆中,以获取其内部值。

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

一些建议:

  1. 避免突变;
  2. 请勿使用x = x + y ,使用x += y相反;
  3. 不要在函数和变量名称中使用驼峰命名法;
  4. 不要使用换行大括号。

关于rust - 如何从 std::cmp::Reverse::<T> 获取 T 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74734489/

相关文章:

string - 无法将 &String 强制转换为 &str

java - 与实现Iterable相关的对象类型有哪些

R中的反转数字

function - 反向函数和 append 函数到自定义列表标准 ml

c# - 如何在 C# 中更改变量类型?

python - Python如何实现str[::-1]?

rust - 如何为盒装值实现迭代器?

json - 用rust反序列化具有多个可能值的JSON

rust - 无法链访问元组类型

javascript - typescript :有没有像联合类型一样工作的东西,除了我们可以访问并非所有联合类型都通用的属性?