C++: 如何遍历并输出unordered_map中的所有键值对

本文将介绍如何使用C++遍历unordered_map并输出所有键值对。unordered_map是C++标准库中提供的一种关联容器,它存储键值对,并允许通过键快速查找对应的值。

以下代码演示了如何遍历unordered_map并输出所有键值对:cpp#include <pcl/point_types.h>#include <unordered_map>#include #include

struct Slice { pcl::PointIndices index; pcl::PointXYZRGB centroid;};

void haxi(pcl::PointCloudpcl::PointXYZRGB::Ptr cloud4, pcl::PointCloudpcl::PointXYZRGB::Ptr cloud5){ std::unordered_map<std::string, Slice> sliceMap; std::vector SALL;

for (int i = 0; i < cluster_centroids->size(); ++i)    {        Slice slices;        SALL.push_back(slices);

    Slice& slice0 = SALL[i];        slice0.index = cluster_indices[i];        slice0.centroid.x = cluster_centroids->points[i].x;        slice0.centroid.y = cluster_centroids->points[i].y;        slice0.centroid.z = cluster_centroids->points[i].z;

    std::string key = std::to_string(slice0.centroid.x) + '_' + std::to_string(slice0.centroid.y) + '_' + std::to_string(slice0.centroid.z);        sliceMap[key] = slice0;    }

// 输出哈希表中所有的键和对应的值    for (auto it = sliceMap.begin(); it != sliceMap.end(); ++it) {        std::cout << 'Key: ' << it->first << std::endl;        std::cout << 'Value: ' << std::endl;        std::cout << '    Index: ' << it->second.index << std::endl;        std::cout << '    Centroid: (' << it->second.centroid.x << ', ' << it->second.centroid.y << ', ' << it->second.centroid.z << ')' << std::endl;    }}

代码解释:

  1. 我们使用基于范围的 for 循环遍历 sliceMap。2. it 是一个迭代器,它指向 sliceMap 中的键值对。3. it->first 获取键,it->second 获取值。4. 我们使用 std::cout 输出键和值。

通过这段代码,您可以清晰地了解如何使用迭代器遍历 unordered_map 并输出所有键值对。

C++: 如何遍历并输出unordered_map中的所有键值对

原文地址: https://www.cveoy.top/t/topic/fK5L 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录