rustHow to iterate btreemap in Rust
Iterating over a BTreeMap in Rust can be done using the iter() method. This method returns an iterator over the entries of the map, which can then be used to access the key-value pairs.
Example code
use std::collections::BTreeMap;
let mut map = BTreeMap::new();
map.insert("a", 1);
map.insert("b", 2);
for (key, value) in map.iter() {
println!("key: {} value: {}", key, value);
}
Output example
key: a value: 1
key: b value: 2
Code explanation
use std::collections::BTreeMap;: imports theBTreeMaptype from thestd::collectionsmodule.let mut map = BTreeMap::new();: creates a new emptyBTreeMap.map.insert("a", 1);: inserts a key-value pair into theBTreeMap.for (key, value) in map.iter() {: starts an iterator loop over the entries of theBTreeMap.println!("key: {} value: {}", key, value);: prints the key and value of the current entry.
Helpful links
Related
- How to do a for loop with index in Rust
- Rust negative for loop example
- Rust parallel loop example
- How to iterate string lines in Rust
- How to iterate through hashmap keys in Rust
- Rust for loop range inclusive example
- How to iterate through hashmap values in Rust
- How to get index in for loop in Rust
- How to iterate in pairs in Rust
More of Rust
- How to replace strings using Rust regex?
- How to match whitespace with a regex in Rust?
- How to use non-capturing groups in Rust regex?
- How to perform matrix operations in Rust?
- Bitwise operator example in Rust
- Regex example to match multiline string in Rust?
- How to use regex lookahead in Rust?
- Using box future in Rust
- How to use regex lookbehind in Rust?
- How to check for equality between Rust slices?
See more codes...