【问题标题】:How to get all keys from STL hash_map?如何从 STL hash_map 获取所有键?
【发布时间】:2012-01-15 16:51:43
【问题描述】:

有没有办法从 STL hash_map 中获取所有键?或者我必须在插入之前使用 set 或 hash_set 之类的东西来记录它们?

【问题讨论】:

  • 请注意,在所有建议的解决方案中,密钥都是无序的(这很好,如果不需要,为什么要排序?)如果您需要它们,则需要 sort 结果

标签: c++ stl hashmap


【解决方案1】:
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);
}

【讨论】:

  • 我认为你的意思是“iter.first”
【解决方案2】:

只需遍历hash_map;对于每次迭代,iter-&gt;first 是关键。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      您可能想要遍历 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;        
      }
      

      【讨论】:

        猜你喜欢
        • 2011-05-23
        • 1970-01-01
        • 2011-01-17
        • 2012-07-01
        • 2016-08-08
        • 2017-10-02
        • 2011-08-19
        • 2010-11-12
        • 1970-01-01
        相关资源
        最近更新 更多