首页 > 解决方案 > 将数组值传递给结构构造函数

问题描述

是否可以以更好的方式将值从数组传递到结构构造函数:

struct A {
std::string a;
std::string b;
};

std::string array[2] = {"looks", "bad"};
A a = {array[0], array[1]};

让它看起来很糟糕,不可读,小的变化会导致很多问题。我不介意使用简单数组之外的其他东西,但我想不出解决这个问题的办法。我正在考虑使用 lambda 来返回数组中的每个值,但我目前正在学习 C++,不知道它是否可能以及是否可以编写代码。

标签: c++structlambdaconstructor

解决方案


如果目标是处理预先存在的数组,那么“更好”的方法是编写构造函数或A接受数组,如下所示:

struct A {
A(const std::vector<std::string>& args) : a(args[0]), b(args[1]) { };
A(const std::string* args) : a(args[0]), b(args[1]) { };
std::string a;
std::string b;
};

第一个版本更可取,因为传递std::vector意味着它包含第二种形式实际上不包含的长度信息。


推荐阅读