-1
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.

paddy
  • 60,864
  • 6
  • 61
  • 103
Charles Chiakwa
  • 184
  • 1
  • 8
  • Hello, many people here watch the C++ tag, expecting questions about C++. I'm interested to know why you have tagged a Rust question as C++. What do you hope to achieve by that? – paddy Jul 20 '23 at 02:12
  • Does this answer your question? [How do I sort a map by order of insertion?](/q/30243100/2189130) Rust's `HashMap` does not preserve insertion order; you would need something like [the indexmap crate](https://github.com/bluss/indexmap) for that. – kmdreko Jul 20 '23 at 02:13

1 Answers1

1

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.

Scott Lang
  • 21
  • 2
  • 1
    I think [`get_index`](https://docs.rs/indexmap/latest/indexmap/map/struct.IndexMap.html#method.get_index) is what would actually help OP. They want to get the item inserted second, so they would call `get_index(1)`. It would also be worth pointing out that using the `remove` method no longer causes the indexes to reflect insertion order. – cdhowie Jul 20 '23 at 04:55