我是一个 C++ 菜鸟,这应该可以解释这个天真的问题。
我需要一个将 Person 转换为 PersonBMI 的函数(或方法),而不是 lambda。
#include <iostream>
#include <vector>
#include <array>
using namespace std;
struct Person
{
float height;
float weight;
int age;
std::string_view name;
};
struct PersonBmi
{
float bmi;
std::string_view name;
};
int main() {
std::array<Person, 4> people {{
{1.7f, 60.2f, 24, "matheus"},
{1.9f, 99.1f, 22, "lucas"},
{1.63f, 57.12f, 27, "linda"},
{1.63f, 123.5f, 47, "drew"}
}};
std::vector<PersonBmi> bmis;
std::transform(begin(people),
end(people),
back_inserter(bmis),
[](auto const& person){
return PersonBmi{
person.weight / (person.height * person.height),
person.name
};
});
return 0;
}
创建适当的转换构造函数
PersonBmi(const Person& person)
并使用 std::copy()
。
#include <algorithm>
#include <array>
#include <iostream>
#include <vector>
using namespace std;
struct Person {
float height;
float weight;
int age;
std::string_view name;
};
struct PersonBmi {
PersonBmi(const Person& person)
: bmi{person.weight / (person.height * person.height)},
name{person.name} {}
float bmi;
std::string_view name;
};
int main() {
std::array<Person, 4> people{{{1.7f, 60.2f, 24, "matheus"},
{1.9f, 99.1f, 22, "lucas"},
{1.63f, 57.12f, 27, "linda"},
{1.63f, 123.5f, 47, "drew"}}};
std::vector<PersonBmi> bmis;
std::copy(begin(people), end(people), back_inserter(bmis));
return 0;
}