2012-01-15 38 views
2

有沒有辦法從STL hash_map獲取所有密鑰?或者我必須使用像set或hash_set之類的東西在插入之前記錄它們?如何從STL hash_map獲取所有密鑰?

+0

注意,在所有提出的解決方案的關鍵是無序的(這是罰款,爲什麼訂單,如果沒有必要?)如果你需要它們,你需要對結果進行排序 – 2012-01-15 17:04:33

回答

6
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); 
} 
+0

我認爲你的意思是「iter.first」 – 2013-07-15 18:03:02

4

簡單地遍歷hash_map;對於每次迭代,iter->first是關鍵。

4

大廈伊戈爾OKS'回答:

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>()); 
0

您可能希望通過的hash_map迭代,並提取一對由當前迭代器價值指向的第一個元素(一對的第一個元素是事實關鍵)。

// 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 
} 

這是一個可能的功能來提取一個的hash_map鍵向量:

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;   
}