簡體   English   中英

從 c++ 中的 unordered_map 訪問值

[英]accessing values from unordered_map in c++

我有一個 unordered_map:

unordered_map<string, list<string>> adj_list;

如何查看字符串list<string>是否包含值?

我試過了:

if(adj_list.find("find")) printf("value found");

但它給了我一個轉換錯誤。 如何訪問此unordered_map中的第一個字符串和第二個字符串列表? 澄清:我有一個值"here" ,它是adj_list中的第一個字符串,我想在屬於"here"的字符串列表中找到"find" ”。

要在std::list中查找元素,您可以使用std::find

std::unordered_map<string, list<string>> adj_list /* = ..*/;

auto it_umap = adl_list.find("here");
if (it_umap != adl_list.end())
{
    auto& words = it_umap->second;
    auto it = std::find(words.begin(), words.end(), "find");
    if (it != words.end()) { std::cout << "value found"; }
}

如果你知道密鑰,你可以這樣做:

auto l = adj_list.find("here"); // here we get the correct list
if(l != adj_list.end())
{
    if(std::find(l->second.begin(), l->second.end(),"find") != l->second.end())
    {
        printf("Found");
    }
}

如果您不知道 map 中正確list<string>的鍵是什么,您可以這樣做:

for(auto it=adj_list.begin(); it != adj_list.end(); ++it)
{
    if(std::find(it->second.begin(), it->second.end(),"find") != it->second.end())
    {
        printf("Found");
    }
}

完整代碼:

#include<iostream>
#include<unordered_map>
#include<list>
#include<string>

int main()
{
    std::unordered_map<std::string, std::list<std::string>> adj_list;
    std::list<std::string> l;
    l.emplace_back("find");

    adj_list.emplace("string", l);
    for (auto it = adj_list.begin(); it != adj_list.end(); ++it)
    {
        if (std::find(it->second.begin(), it->second.end(), "find") != it->second.end())
        {
            printf("Found");
        }
    }
    return 0;
}

如果您想搜索具有“here”鍵的列表,請執行(假設您知道“here”條目確實存在)

auto &here = adl_list["here"];
if (std::find(here.begin(), here.end(),"find") != here.end())
{
    std::cout << "found";
}

如果它可能不存在那么做

auto &lookup= adl_list.find("here");
if(lookup != adl_list.end())
{
   auto &here = lookup.second;
   if (std::find(here.begin(), here.end(),"find") != here.end())
   {
     std::cout << "found";
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM