【问题标题】:How to access value of a key in hash map如何访问哈希映射中键的值
【发布时间】:2016-09-15 05:02:01
【问题描述】:

我正在尝试访问特定哈希键的值。示例代码如下。 Test Here

// unordered_map::at
#include <iostream>
#include <string>
#include <unordered_map>

int main ()
{
  std::unordered_map<std::string,int> hashmap = {
                { "Apple", 300},
                { "Banana", 60},
                { "Orange", 70 } };

  std::cout << "Value :" << hashmap[300]<<std::endl;

  return 0;
}

但是,当我尝试访问特定值的密钥时,它可以正常工作,例如 hashmap["Apple"],它提供 300,即 Apple 的密钥。如何让它像hashmap[300]一样工作,给“Apple”。

【问题讨论】:

标签: c++ hashmap


【解决方案1】:

如何使它工作,如hashmap[300]"Apple"

哈希映射是单向的:key --&gt; value。如果您需要两个方向都快,则需要不同的数据结构(如Boost.Bimap)。

如果您只是希望查找工作周期并且对线性性能没问题,那么您可以使用std::find_if

auto it = std::find_if(hashmap.begin(), hashmap.end(),
    [](auto const& pr){ return pr.second == 300; });
if (it != hashmap.end()) {
    std::cout << "Key for 300: " << it->first;
}

std::unordered_map 中没有任何基于查找值的内容。

【讨论】:

  • 谢谢,Boost.Bimapstd::unordered_map 一样快
  • @AaghazHussain 这不可能。
  • 它可能没有相当那么快,但它可能并不遥远(换句话说,O(1),而不是 O(n))。跨度>
【解决方案2】:

如您所料,没有直接访问。

其中一种方法是使用std::find_if

//DATA
std::unordered_map<std::string,int> hashmap = {

            {"Apple", 300},
            {"Banana",60},
            {"Orange",70}
};


//FIND BASED ON GIVEN INPUT
const auto& foundItem = std::find_if(hashmap.begin(),hashmap.end(),
                [](const std::pair<std::string,int>& item)
                {
                    return item.second == 300;
                });

std::cout<<foundItem->first<<std::endl;

此外,当您在无序映射中查找值时,可能会有另一个键具有相似的值。

例如另一个元素{"grape",300}。如果你想要所有值为 300 的键......

//DATA
std::unordered_map<std::string,int> hashmap = {

              {"Apple", 300},
              {"Banana",60},
              {"Orange",70},
              {"Grape",300}
};

//RESULT
std::vector<std::string> foundValues;

//FIND BASED ON GIVEN INPUT
std::for_each(hashmap.begin(),hashmap.end(),
                 [&foundValues](const std::pair<std::string,int>& item)
                 {
                       if(item.second == 300)
                           foundValues.push_back(item.first);

                 });

 //JUST TO TEST
 std::cout<<foundValues[0]<<"   "<<foundValues[1]<<std::endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-22
    • 2014-10-06
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 2011-09-30
    • 2016-01-31
    相关资源
    最近更新 更多