我正在linspase
使用以下输入结构创建一个标题为C ++ 17的函数linspace(double upper, double lower, int size)
。函数应size
在lower
和之间创建均匀间隔的数字upper
。编程此功能很容易;但是,我希望它创建一个std::array<double, size>
函数,该函数将根据函数调用确定数组大小并传递数据类型std::array<double, size>
。我知道模板是执行此操作的唯一方法,但是我不确定如何构建模板。在一般的伪代码中,我认为它看起来像这样。
template <typedef T, size_t size>
T linspace(double lower, double upper, int num)
{
/* ... Function meat goes here to create arr of size
num of evenly space numbers between lower and upper
*/
return arr
}
但是,我知道此模板声明不正确,并且我不确定它的外观。明确地说,我希望它返回std:;array
特定大小的,而不是std::vector
。
如果(正确)将数组大小作为模板参数传递,则不需要将其作为函数参数之一,因此:
template <size_t size>
auto linspace(double lower, double upper) -> std::array<int, size>
{
std::array<int, size> arr{};
//populate the array ...
return arr;
}
由于您使用的是c ++ 14,因此可以完全摆脱返回值,并拥有一个类似以下的原型:
template <size_t size>
auto linspace(double lower, double upper)
然后,您可以像这样使用它:
auto arr = linspace<1>(0, 1);
for(auto a : arr)
{
std::cout << a << std::endl;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句