在Rust的HashMap中,是否有一种通过索引获取插入的键和值的方法?

huangapple go评论67阅读模式
英文:

Is there a way to get inserted key and value by index in Rust HashMaps?

问题

use std::collections::HashMap;

fn main() {
    let mut map: HashMap<char, u64> = HashMap::new();
    map.insert('a', 1);
    map.insert('c', 2);
    map.insert('b', 3);

    // 我如何获取字符 'c' 和值 2,因为它是添加到映射中的第二个值
}
英文:
use std::collections::HashMap;


 fn main() {
    let mut map: HashMap&lt;char, u64&gt; = HashMap::new();
     map.insert(&#39;a&#39;, 1);
     map.insert(&#39;c&#39;, 2);
     map.insert(&#39;b&#39;, 3);

    // How can I get char &#39;c&#39; and value 2 since its the second value added to the map

 }

I tried getting the keys and values from the hashmap and but they are not returned in right order in which they are added.

答案1

得分: 1

Rust的HashMap不会保持插入顺序。您可以使用indexmap crate来实现这一点。您可以使用IndexMap::get_full方法来获取键、值和该键的索引。

英文:

Rust's HashMap doesn't maintain the order of insertion. You can use indexmap crate to do this. You can use the IndexMap::get_full method to get the key, the value, and the index of that key.

huangapple
  • 本文由 发表于 2023年7月20日 10:07:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76726230.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定