繁体   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