如何将 std::map 值复制到非容器数组中

How to copy std::map value into non-container array?

本文关键字:数组 std map 复制      更新时间:2023-10-16

我有一个填充了id和浮点数组的地图。我想将浮点数(pair.second(复制到 *temp_arr 中。

// Temp object
struct Temp
{
    float t1, t2, t3; 
    float n1, n2, n3;
};
// A map that is populated.
std::map<int, Temp> temps;
// temps gets populated ...
int i = 0;
Temps *temp_arr = new Temp[9];
// currently, I do something like ...
for (auto& tmp : temps)
    temp_arr[i++] = tmp.second;
// here's what I tried ...
std::for_each(temps.begin(), temps.end(), [&](std::pair<int, Temp> &tmp) {
        temp_arr[i++] = tmp.second;
});   

我试图使用 std::copy 来做到这一点,我认为需要一个 lambda 才能将 tmp.seconds 的映射放入temp_arr,但到目前为止,还没有。

std::copy在这里不合适。 相反,您可以使用std::transform

std::transform(temps.begin(), temps.end(), temp_arr,
               [](const std::pair<const int, Temp>& entry) {
                   return entry.second;
               });