簡體   English   中英

訪問 unordered_map c++​​ 的值(數組)

[英]Access the values (array) of unordered_map c++

我正在嘗試在 C++ 中使用 unordered_map,這樣,對於鍵,我有一個字符串,而對於值,有一個浮點數組。

std::unordered_map<std::string, std::array<float, 3>> umap;

但是,我不確定如何訪問值數組。 我知道要訪問元素,迭代器是一個選項,但是如何具體訪問數組的元素?

我正在嘗試將這些數組值分配給不同的數組(std::array mapArrayVal)

我嘗試使用

for (auto i = umap.begin(); i != umap.end(); i++)   
 {
   std::array<float, 3> mapArrayVal = (i->second.first, i->second.second, 
     i>second.third);
 }

是正確的方法嗎? 任何幫助表示贊賞,TIA!

此示例向您展示了如何使用一些注釋來幫助您完成此操作:

#include <array>
#include <iostream>
#include <string>
#include <unordered_map>

int main()
{
    // a map consists of key,value pairs in your case
    // the key will have a type of std::string
    // the value will be an std::array (with three entries)
    std::unordered_map<std::string, std::array<float, 3>> umap{ 
        {"key1", {1.0,2.0,3.0}},
        {"key2", {4.0,5.0,6.0}}
    };

    // iterate over all entries using an explicitly type it
    // normally you would type auto i.o. std::unordered_map<std::string, std::array<float, 3>>::iterator
    // but this shows all the types involved
    for (std::unordered_map<std::string, std::array<float, 3>>::iterator it = umap.begin(); it != umap.end(); ++it)
    {
        // access key/values by iterator it->second will be the array
        std::cout << "key = `" << it->first << "`, values : {" << (it->second)[0] << ", " << (it->second)[1] << ", " << (it->second)[2] << "}\n";
    }

    // however with c++ you could do it in a much more readable way
    // combine range based for loop : https://en.cppreference.com/w/cpp/language/range-for
    // with structured binding : https://en.cppreference.com/w/cpp/language/structured_binding
    // the key_value_pair is const since you only want to observe it for printing
    for (const auto& [key, values] : umap)
    {
        std::cout << "key = `" << key << "`, values : {" << values[0] << ", " << values[1] << ", " << values[2] << "}\n";
    }

    // use at(key) in map don't use operator[] it may insert an "empty" item in the map if something isn't found there!
    auto& reference_to_array_in_map = umap.at("key1"); 
    
    // this is how you make a copy of the array
    std::array<float, 3> copied_values{ reference_to_array_in_map };
    for (const float value : copied_values)
    {
        std::cout << value << " ";
    }
    std::cout << "\n";

    return 0;
}

暫無
暫無

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

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