c++ - 通过代码构造 std::array 并初始化元素对象
问题描述
我想初始化我的数组项,同时避免不必要的实例和副本(类似于这个问题:initialize std::array without copying/moving elements)。
初始化列表确实适用于少量对象。
位我想通过代码片段来做到这一点,因为我的数组有数百个项目......
我怎样才能做到这一点?
#include <array>
#include <iostream>
class mytype {
public:
int a;
mytype() : a(0) {}
mytype(int a) : a(a) {}
};
int main() {
// explict constructor calls to instantiate objects does work
std::array<mytype, 2> a = { { mytype(10), mytype(20) } };
std::cout << a[0].a; // 10
// I want to do something like this - what does not work of course
std::array<mytype, 2> b = { { for (i = 0, i++, i < 2) mtype(10 * i); } };
}
解决方案
这通常通过一对模板来完成:
namespace detail {
template<std::size_t... Idx>
auto make_mytype_array(std::index_sequence<Idx...>) {
return std::array<mytype, sizeof...(Idx)>{{
mytype(10 * Idx)...
}};
}
}
template<std::size_t N>
auto make_mytype_array() {
return detail::make_mytype_array(make_index_sequence<N>{});
}
以上是一对实用程序免费函数,但如果需要,可以折叠到类中。如果您需要的不仅仅是像这样的表达式10*i
,那么可以将 lambda 作为另一个参数传递(模板化为一般的“可调用”)。使用复制省略,这将全部折叠为结果数组对象的直接初始化。
推荐阅读
- scala - 如何在直接 Spark SQL 中指定基于结构化流时间的窗口
- excel - 当单元格范围没有特定长度时显示 MsgBox
- django - Django URL 参数相互替换
- python - 复制pandas加权平均计算的分子和分母的案例
- python - 如何在 python 神经网络中执行具有多个类的单类分类?
- c - 键盘输入错误地重定向到命名管道读取
- python - Google Cloud NL 实体识别器将单词组合在一起
- azure-cognitive-search - Azure 搜索索引器与使用高水印列的 Azure SQL 数据源产生低效查询
- python - 使用 .index 删除 pandas 中的行
- vba - 将活动单元格值分配给过滤器作为另一个工作表中的条件