我有一个编码方案,其中使用以下规则转换数字0-9:
0-3 1-7 2-2 3-4 4-1 5-8 6-9 7-0 8-5 9-6
因此,我可以使用以下数组进行正向查找
int forward[] = { 3,7,2,4,1,8,9,0,5,6}
其中,forward[n]是n的编码。类似地,下面是反向查找的编码
int inverse{ 7,4,2,0,3,8,9,1,5,6};
其中`逆将解码n
逆向数组可以很容易地在运行时从前向数组创建,但理想情况下,我希望在编译时创建它。考虑到模板元编程是一种函数式语言,我首先用Haskell实现了所有东西:
pos :: [Int] -> Int -> Int
pos lst x =
let
pos'::[Int] -> Int -> Int -> Int
pos' (l:lst) x acc
| l == x = acc
| lst == [] = -1
| otherwise = pos' lst x (acc + 1)
in
pos' lst x 0
inverse ::[Int] -> [Int]
inverse lst =
let
inverse'::[Int] -> Int -> [Int]
inverse' l c
| c == 10 = []
| otherwise = pos l c : inverse' l (c + 1)
in
inverse' lst 0 我设法在pos模板元编程中实现了C++,使用:
#include <iostream>
static int nums[] = {3,7,2,4,1,8,9,0,5,6};
template <int...>
struct pos_;
template <int Find, int N, int Arr0, int... Arr>
struct pos_<Find,N, Arr0, Arr...> {
static constexpr int value = pos_<Find, N+1, Arr...>::value;
};
template <int Find, int N, int... Arr>
struct pos_<Find ,N, Find, Arr...> {
static constexpr int value = N;
};
template <int Find,int N>
struct pos_<Find ,N> {
static constexpr int value = -1;
};
template <int Find, int... Arr>
struct pos {
static constexpr int value = pos_<Find,0, Arr...>::value;
};
int main()
{
std::cout << "the positions are ";
std::cout << pos<3, 3,7,2,4,1,8,9,0,5,6>::value << std::endl;
}但是,我很难将数组转换为参数包,当涉及到实现逆时,我不能将value分配给参数包。
在模板元编程中使用列表的最佳方法是什么?
对于上下文,在查看Base64编码时想到了这个问题,我想知道是否有一种编译时生成反向编码的方法。
发布于 2018-07-31 11:41:09
在编译时生成逆数组的最简单/最干净的方法是编写constexpr逆函数。大致如下:
template<size_t N>
constexpr std::array<int, N> inverse(const std::array<int, N> &a) {
std::array<int, N> inv{};
for (int i = 0; i < N; ++i) {
inv[a[i]] = i;
}
return inv;
}您可以在这里看到它的作用:https://godbolt.org/g/uECeie
如果您想要更接近您最初的方法/Haskell,您只需查找如何使用TMP实现编译时列表,以及如何为它们编写熟悉的函数(比如追加和连接)。在那之后,实现逆就变得微不足道了。顺便说一句,忽略了一般的C++语法笨拙,这些定义在精神上将与您在函数式语言中所发现的非常相似。
https://stackoverflow.com/questions/51612153
复制相似问题