在不使用 lambda 的情况下将一个结构的容器转换为另一个结构的容器

问题描述 投票:0回答:1

我是一个 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;
}
c++ lambda containers
1个回答
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;
}
© www.soinside.com 2019 - 2024. All rights reserved.