通过模板生成排列

发布于 2024-09-08 05:31:39 字数 689 浏览 5 评论 0原文

我想要一个函数或函数对象,它可以使用编译时指定的排列生成其输入的排列。需要明确的是,我并不希望生成所有排列,而只是生成一种特定排列。例如,permute<1,4,3,2>(a, b, c, d) 将返回 (a,d,c,b)。显然,使用特定长度(例如 2)的排列来做到这一点很简单,就像这样

#include <boost/tuple.hpp>
template< unsigned a, unsigned b>
struct permute {
    template< class T >
    boost::tuple< T, T > operator()( T ta, T tb ) {
        boost::tuple< T, T > init = boost::make_tuple( ta, tb );
        return boost::make_tuple( init.get< a >(), init.get< b >() );
    }
};

但是,我将如何针对任意长度的排列执行此操作?另外,是否有更清晰的方式来编写上述代码?是的,上面的代码不限于进行排列,因为允许 permute<2,2>(a,b) ,但我不认为这是一个缺陷。但是,是否可以限制为只允许实际排列?

I'd like a function, or function object, that can generate a permutation of its inputs with the permutation specified at compile time. To be clear, I am not looking to generate all of the permutations, only a specific one. For instance, permute<1,4,3,2>( a, b, c, d ) would return (a,d,c,b). Obviously, it is straightforward to do this with a permutation of a specific length, e.g. 2, like this

#include <boost/tuple.hpp>
template< unsigned a, unsigned b>
struct permute {
    template< class T >
    boost::tuple< T, T > operator()( T ta, T tb ) {
        boost::tuple< T, T > init = boost::make_tuple( ta, tb );
        return boost::make_tuple( init.get< a >(), init.get< b >() );
    }
};

But, how would I go about doing this for an arbitrary length permuation? Also, is there a cleaner way of writing the above code? Yes, the above code is not restricted to making permutations as permute<2,2>(a,b) is allowed, but I don't see that as a flaw. However, can it be restricted to only allowing actual permutations?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心的憧憬 2024-09-15 05:31:39

C++0x 提供了可变参数模板,您应该能够使用它来处理任意长度的排列。它们是专门添加的,因为当前版本的 C++ 没有一个干净的方法来处理此类问题。

C++0x provides variadic templates, which you should be able to use to handle an arbitrary length permutation. They were added specifically because the current version of C++ doesn't have a clean way of dealing with this kind of problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文