简体   繁体   中英

How does c++ stl unordered_map print all its values?

I am using the c++ stl unordered_map library for some leetcode question. I can use find function and [] operator overload to access my elements. but I've seen some answers using a for loop to iterate through all the elements of the hashmap. From my understanding the inner structure of a hashmap is a vector usually and this vector will never be fully used(meaning there will be empty slots to have constant big O from not having too much collision). But from the answers I am seeing people are iterating over the vector but they are not printing these empty indexes because I don't see any garbage values. I don't understand how this is possible. Here is the code i've seen.

vector<vector<string>> groupAnagrams(vector<string>& strs) {
        unordered_map<string, vector<string>> mp;
        for (string s : strs) {
            mp[t].push_back(s);
        }
        vector<vector<string>> anagrams;
        for (auto p : mp) {  //this is the part I don't understand
            anagrams.push_back(p.second);
        }
        return anagrams;
    } 

I would expect iterating over each element of the underlying vector of the hashmap data structure to have garbage values because not all members are filled in the vector, but the result doesn't include these values and only gives the correct output. I don't understand how.

From your question, it seems like you might think that an iterator to an STL container iterates straightforwardly over the underlying data structure. That is not the case. The iterator itself can contain fields and logic to allow it to iterate in a logical manner.

The standard library doesn't dictate algorithm implementations, but all common can support iteration without going over empty elements:

  1. The closed-table implementation you wrote about (which is not used in practice by implementations of the STL), has an array of entries, each of which is taken or not. Each entry can be marked as taken either by having an array of pairs (one for the value, and one for a boolean), or by using two arrays. In any case, when iterating, the iterator simply bypasses, when incremented, all entries that are not taken.

  2. A more common implementation is an array of linked lists. Here, the iterator contains both the position within the array, and the link of the list. When incremented, it attempts to move to the next link. If none exists, it moves to the next list that is nonempty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM