[英]How to get all keys from STL hash_map?
Is there any way to get all keys from an STL hash_map? 有没有办法从STL hash_map获取所有密钥? Or I have to use something like set or hash_set to record them before insertion?
或者我必须使用set或hash_set之类的东西在插入之前记录它们?
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);
}
Simply iterate over the hash_map
; 只需遍历
hash_map
; for each iteration, iter->first
is the key. 对于每次迭代,
iter->first
是关键。
Building on Igor Oks' answer: 以Igor 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>());
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). 您可能想要遍历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
}
This is a possible function to extract keys from a hash_map to a vector: 这是一个将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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.