lastland
lastland

Reputation: 910

How to get all keys from STL hash_map?

Is there any way to get all keys from an STL hash_map? Or I have to use something like set or hash_set to record them before insertion?

Upvotes: 2

Views: 13288

Answers (4)

user1149224
user1149224

Reputation:

You may want to iterate through the hash_map, and extract the first element from the pair pointed by current iterator value (the first element of the pair is in fact a key).

// Assuming that hm is an instance of hash_map:
for (auto it = hm.begin(); it != hm.end(); ++it) // for each item in the hash map:
{
    // it->first is current key
    // ... you can push_back it to a vector<Key> or do whatever you want
}

This is a possible function to extract keys from a hash_map to a vector:

template <typename Key, typename Type, typename Traits, typename Allocator>
vector<Key> extract_keys(const hash_map<Key, Type, Traits, Allocator> & hm)
{
    vector<Key> keys;

    // If C++11 'auto' is not available in your C++ compiler, use:
    // 
    //   typename hash_map<Key, Type, Traits, Allocator>::const_iterator it;
    //   for (it = hm.begin(); ...)
    //
    for (auto it = hm.begin(); it != hm.end(); ++it)
    {
        keys.push_back(it->first);
    }

    return keys;        
}

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249123

Building on Igor Oks' answer:

hash_map<string, void *> hashMap;

vector<string> keys;
keys.reserve(hashMap.size());

transform(hashMap.begin(), hashMap.end(), back_inserter(keys),
    select1st<hash_map<string, void*>::value_type>());

Upvotes: 4

Jon
Jon

Reputation: 437336

Simply iterate over the hash_map; for each iteration, iter->first is the key.

Upvotes: 4

Igor
Igor

Reputation: 27250

hash_map<string, void *> hashMap;

vector<string> keys;
keys.reserve(hashMap.size());

for (hash_map<string, void *>::iterator iter = hashMap.begin(); 
                                        iter != hashMap.end(); 
                                        ++iter)
{
    keys.push_back(iter->first);
}

Upvotes: 7

Related Questions