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

时间:2019-07-14 19:18:56

标签: c++ c++11

我有一个地图,其中填充了一个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中,但是到目前为止,还没有。

1 个答案:

答案 0 :(得分:3)

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

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