如何从STL hash_map中获取所有密钥
How to get all keys from STL hash_map?
有什么方法可以从STL hash_map中获取所有密钥吗?或者我必须在插入之前使用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);
}
只需迭代hash_map
;对于每次迭代,iter->first
是关键。
基于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>());
您可能想要遍历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;
}
相关文章:
- 获取当前密钥状态?
- 从std::map值中获取密钥的有效方法
- 获取 CLSID 密钥问题
- C++ std::map:获取特定偏移量的密钥
- 从密钥代码(X11 XGrabKey)获取密钥名称
- GLFW 获取密钥"esc"并关闭窗口
- 函数从单向链表和错误服务中获取密钥
- QSSLCertificatifific如何获取Windows中显示的公共密钥
- 获取原始密钥,就像没有移位修饰符一样
- 将 map
转换为 void* 并返回并获取密钥 - 有没有任何方法可以从C++中的char中获取虚拟密钥代码
- 如何从虚拟密钥代码中获取密钥文本
- C++ 获取同步密钥状态状态问题
- 检查是否在映射 C++ 中找到并获取密钥
- 如何使用 C++11 中的函数式编程从映射中获取密钥
- CM_Get_DevNode_Property_Keys是否有获取密钥名称的方法
- 如何从STL hash_map中获取所有密钥
- 从WM_CHAR消息中获取虚拟密钥代码
- 如何在CryptoAPI中通过证书公钥获取密钥容器的信息
- 以"simple"形式获取 RSA 密钥