c++ - 将数组值传递给结构构造函数
问题描述
是否可以以更好的方式将值从数组传递到结构构造函数:
struct A {
std::string a;
std::string b;
};
std::string array[2] = {"looks", "bad"};
A a = {array[0], array[1]};
让它看起来很糟糕,不可读,小的变化会导致很多问题。我不介意使用简单数组之外的其他东西,但我想不出解决这个问题的办法。我正在考虑使用 lambda 来返回数组中的每个值,但我目前正在学习 C++,不知道它是否可能以及是否可以编写代码。
解决方案
如果目标是处理预先存在的数组,那么“更好”的方法是编写构造函数或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
意味着它包含第二种形式实际上不包含的长度信息。
推荐阅读
- php - 如何仅在数组中传递邮政编码
- google-bigquery - 按应用从 BigQuery 获取专利的前向引用数据
- jquery - Adobe DTM:事件规则 | 捕获数据属性
- javascript - 将按ASCII顺序排序的一维数组转换为Javascript中的嵌套数组
- amazon-web-services - 估计 SQS 处理时间和负载
- angular - Angular 5:如何在子组件中获取父组件路由参数?
- spring - 邮递员 - 查看压缩响应大小的选项..?
- android - API > 22 的 TextInputLayout 线条颜色不会以编程方式更改
- mongodb - 如何制定正确的 mongo 查询以获取正确格式的记录
- javascript - 上传前的javascript预览图像