[英]Access the values (array) of unordered_map c++
I am trying to use the unordered_map in C++, such that, for the key I have a string, while for the value there is an array of floats.我正在尝试在 C++ 中使用 unordered_map,这样,对于键,我有一个字符串,而对于值,有一个浮点数组。
std::unordered_map<std::string, std::array<float, 3>> umap;
But, I am not sure how to access the array of values.但是,我不确定如何访问值数组。 I know to access the elements, an iterator is an option, but how specifically elements of an array can be accessed?
我知道要访问元素,迭代器是一个选项,但是如何具体访问数组的元素?
I am trying to assign these array values to different array (std::array mapArrayVal)我正在尝试将这些数组值分配给不同的数组(std::array mapArrayVal)
I tried using我尝试使用
for (auto i = umap.begin(); i != umap.end(); i++)
{
std::array<float, 3> mapArrayVal = (i->second.first, i->second.second,
i>second.third);
}
is the correct way?是正确的方法吗? Any help is appreciated, TIA!
任何帮助表示赞赏,TIA!
This example shows you how to do it with some comments to help you on your way :此示例向您展示了如何使用一些注释来帮助您完成此操作:
#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.