C++访问unordered_map中std::array类型值并赋值的正确方法
原代码问题说明
你写的实现完全无法通过编译,存在3个明确错误:
std::array<float, 3>是固定长度数组的封装,没有first/second/third成员,这类成员是std::pair、std::tuple特有的,直接调用会报编译错误。- 你写的
(i->second.first, i->second.second, i>second.third)是逗号表达式,运行逻辑是从左到右执行每个子表达式,最终只返回最后一个子表达式的结果,根本无法完成数组的整体赋值。 - 代码存在笔误:第三个元素访问写的是
i>second,缺少-,正确的迭代器成员访问应该是i->second。
正确实现方法
std::array本身支持拷贝构造、拷贝赋值,如果你需要把遍历到的数组值整体赋值给目标变量,不需要逐个访问元素,直接赋值即可:
for (auto it = umap.begin(); it != umap.end(); ++it) { // it->second 就是当前键值对中存储的std::array<float,3>类型值,直接拷贝赋值 std::array<float, 3> mapArrayVal = it->second; // 如果需要访问数组内的单个float元素,用[]下标即可,索引从0开始 // float x = mapArrayVal[0]; // float y = mapArrayVal[1]; // float z = mapArrayVal[2]; }
如果你确实需要逐个取出数组内的元素赋值,通过下标运算符访问即可,不要误用pair的成员:
for (auto it = umap.begin(); it != umap.end(); ++it) { std::array<float, 3> mapArrayVal; mapArrayVal[0] = it->second[0]; mapArrayVal[1] = it->second[1]; mapArrayVal[2] = it->second[2]; }
C++11及之后的版本可以用更简洁的范围for写法,减少迭代器相关的代码冗余:
// 用const引用遍历,避免不必要的键值对拷贝 for (const auto& kv : umap) { // kv.first是当前元素的string类型键,kv.second是对应的array值 std::array<float, 3> mapArrayVal = kv.second; }
补充说明:
unordered_map的迭代器指向的元素类型是std::pair<const 键类型, 值类型>,所以迭代器的first成员永远对应键,second成员永远对应存储的值,不要把pair的成员和值类型自身的成员混淆。
内容的提问来源于stack exchange,提问作者P Pp
相关产品推荐
相关产品推荐

