英文:
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<char, u64> = HashMap::new();
map.insert('a', 1);
map.insert('c', 2);
map.insert('b', 3);
// How can I get char 'c' 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论