prosyslab-classroom / cs348-information-security

61 stars 10 forks source link

[Question][Hw2] How to initialize `Hashtbl` with multiple values #247

Closed m-spitfire closed 1 year ago

m-spitfire commented 1 year ago

Name: Murad Bashirov

Hello. I'm looking for a way to initialize Hashtbl with many values. But after searching a lot, I couldn't find anything, so does that mean I can't initialize Hashtbl from given values? I am specifically looking for something like this, I give a list of tuples and it just creates the Hashtbl. I don't want to have 225 calls to Hashtbl.add.

Thanks.

KihongHeo commented 1 year ago

Loop is your best friend: List.iter or List.fold_left

bonjune commented 1 year ago

extend vs. insert

There is no magic. See how the From trait is implemented (https://doc.rust-lang.org/src/std/collections/hash/map.rs.html#1357-1373).

impl<K, V, const N: usize> From<[(K, V); N]> for HashMap<K, V, RandomState>
where
    K: Eq + Hash,
{
    fn from(arr: [(K, V); N]) -> Self {
        Self::from_iter(arr)
    }
}

The from function execute Self::from_iter, and the function is just like this:

impl<K, V, S> FromIterator<(K, V)> for HashMap<K, V, S>
where
    K: Eq + Hash,
    S: BuildHasher + Default,
{
    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> HashMap<K, V, S> {
        let mut map = HashMap::with_hasher(Default::default());
        map.extend(iter);
        map
    }
}

And, of course extend function generally behaves like:

(https://docs.rs/hashbrown/latest/src/hashbrown/map.rs.html#6494-6509)

    fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
        let iter = iter.into_iter();
        let reserve = if self.is_empty() {
            iter.size_hint().0
        } else {
            (iter.size_hint().0 + 1) / 2
        };
        self.reserve(reserve);
        iter.for_each(move |(k, v)| {
            self.insert(k, v);
        });
    }

extend iterates elements and insert them one by one.

API?

If you are looking for a convenient API to build a hash table from the list, you use

m-spitfire commented 1 year ago

I see @bonjune , thanks for the detailed reply. I thought From was somehow creating the Hashmap at once, instead of iterating and mutating it over again.