查找表与constexpr

nbu*_*bis 12 c++ constexpr c++11

我正在寻找创建一个坐标查找表,如:

int a[n][2] = {{0,1},{2,3}, ... }
Run Code Online (Sandbox Code Playgroud)

对于给定的n,在编译时创建.我开始研究constexpr,但似乎是一个函数返回a constexpr std::vector<std::array <int, 2> >不是一个选项,因为我得到:

invalid return type 'std::vector<std::array<int, 2ul> >' of constexpr function
Run Code Online (Sandbox Code Playgroud)

如何创建这样的编译时数组?

Ice*_*ire 20

使用C++ 14,您不需要太多的模板魔法.这里有一个如何使用查找表的示例,f(x) = x^3第一个坐标是x值,第二个坐标是f(x)值:

#include <iostream>

template<int N>
struct Table
{
    constexpr Table() : values()
    {
        for (auto i = 0; i < N; ++i)
        {
            values[i][0] = i;
            values[i][1] = i * i * i;
        }
    }
    int values[N][2];
};

int main() {
    constexpr auto a = Table<1000>();
    for (auto x : a.values)
        std::cout << "f(" << x[0] << ") = " << x[1] << '\n';
}
Run Code Online (Sandbox Code Playgroud)

  • `constexpr Table() : values()`中的`: values()`是什么意思?它是零初始化还是什么? (2认同)

dyp*_*dyp 15

我将首先转储代码,稍后在必要/适当时添加引用和注释.如果结果与您正在寻找的结果有些接近,请发表评论.

通过Xeo这个答案中修改使用std::size_t代替扩展的包扩展(这里需要应用生成器)的指示技巧unsigned.

#include <cstddef>

// by Xeo, from https://stackoverflow.com/a/13294458/420683
template<std::size_t... Is> struct seq{};
template<std::size_t N, std::size_t... Is>
struct gen_seq : gen_seq<N-1, N-1, Is...>{};
template<std::size_t... Is>
struct gen_seq<0, Is...> : seq<Is...>{};
Run Code Online (Sandbox Code Playgroud)

发电机功能:

#include <array>

template<class Generator, std::size_t... Is>
constexpr auto generate_array_helper(Generator g, seq<Is...>)
-> std::array<decltype(g(std::size_t{}, sizeof...(Is))), sizeof...(Is)>
{
    return {{g(Is, sizeof...(Is))...}};
}

template<std::size_t tcount, class Generator>
constexpr auto generate_array(Generator g)
-> decltype( generate_array_helper(g, gen_seq<tcount>{}) )
{
    return generate_array_helper(g, gen_seq<tcount>{});
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

// some literal type
struct point
{
    float x;
    float y;
};
// output support for `std::ostream`
#include <iostream>
std::ostream& operator<<(std::ostream& o, point const& p)
{  return o << p.x << ", " << p.y;  }

// a user-defined generator
constexpr point my_generator(std::size_t curr, std::size_t total)
{
    return {curr*40.0f/(total-1), curr*20.0f/(total-1)};
}

int main()
{
    constexpr auto first_array = generate_array<5>(my_generator);
    constexpr auto second_array = generate_array<10>(my_generator);

    std::cout << "first array: \n";
    for(auto p : first_array)
    {
        std::cout << p << '\n';
    }
    std::cout << "========================\n";

    std::cout << "second array: \n";
    for(auto p : second_array)
    {
        std::cout << p << '\n';
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 哇 - 这是很多代码!这真的是最短的方法吗? (2认同)