c++ - 使用 lambdas 初始化多维数组

标签 c++ arrays c++11 lambda initialization

我想初始化一个 double 组,其中包含两个 3D vector 的三个系数中每一个的前 4 次幂。我现在正在尝试这样的事情:

auto getPows = [](double x) { return {1.,x, x*x, x*x*x, x*x*x*x};};
const double allPows[2][3][5] = {
  {getPows(vec1.x()),getPows(vec1.y()),getPows(vec1.z())},
  {getPows(vec2.x()),getPows(vec2.y()),getPows(vec2.z())}
};

但它给出了一个编译错误:

error: returning initializer list

我读到 lambda 不能隐式返回初始化列表。将 lambda 定义更改为:

auto getPows = [](double x) -> std::initializer_list<double> { return {...};};

没有帮助:

error: cannot convert ‘std::initializer_list<double>’ to ‘const double’ in initialization

正确的做法是什么?

最佳答案

I've read that lambdas cannot return initializer list implicitly. Changing lambda definition to [...] doesn't help

问题是 std::initializer_list 是一个(轻量级)类,而不是初始化列表。

我的意思是...如果您使用初始化列表来初始化一个旧的 C 风格数组,一切顺利

int a[] = { 1, 2, 3 }; // compile

但是如果你使用一个std::initializer_list对象,你会得到一个编译错误

int b[] = std::initializer_list<int>{ 1, 2, 3 }; // compilation error

What's the right way to do it?

您标记了 C++11,您正在使用 std::intializer_list 并且您正在使用 lambda 函数...

恕我直言,您应该使用 std::array 而不是旧的 C 风格数组来完成最后一步。

我的意思是

#include <array>

int main ()
 {
   auto getPows = [](double x) -> std::array<double, 5u>
                     { return {{ 1., x, x*x, x*x*x, x*x*x*x }}; };

   std::array<std::array<std::array<double, 5u>, 3u>, 2u>
    {{ {{ getPows(1.0), getPows(2.0), getPows(3.0) }},
       {{ getPows(0.1), getPows(0.2), getPows(0.3) }} }};
 }

关于c++ - 使用 lambdas 初始化多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51459444/

相关文章:

c++ - c++中operator->()的定义

c++ - VS 2008 中未捕获 HRESULT 异常

c++ - 对类静态 constexpr 结构的 undefined reference ,g++ vs clang

c++ - 返回 std::stringstream - 编译失败

c++ - 为什么 `using`关键字不能用于静态类成员?

c++ - boost 序列化 - 序列化 std::tr1::shared_ptr?

c++ - Boost 侵入式哈希表

javascript - 错误:Object is not a function for returning an array to my callback function

arrays - 确保相邻位置没有两只猫或狗所需的最少交换次数

javascript - 如何使用 JavaScript 评估集合包含测试?