【问题标题】:What is the time complexity of element access for boost::hana::tuple?boost::hana::tuple 的元素访问时间复杂度是多少?
【发布时间】:2017-01-28 23:55:00
【问题描述】:

据我所知,对于纯函数序列类型,序列的幼稚实现将导致元素访问的 O(n) 时间复杂度和更好的实现(如 Chris Okasaki 所述)享受 O(log n ) 复杂度,对于长度为 n 的序列。

operator[] 访问boost::hana::tuple 中的任意元素的时间复杂度是多少?如果以上都不是,那它是如何实现的呢?

【问题讨论】:

  • 如果文档 boost::hana 在概念上与std::tuple 相似,则为 O(1)
  • 我不明白为什么它会是 O(1)(在运行时)。
  • 运行时间还是编译时间?
  • 文档的图表“转换的运行时行为”(boostorg.github.io/hana/index.html#tutorial-performance) 向我建议 O(1),否则 hana::tuple 的图表最终会呈指数级偏离,对吗?我们基本上可以在这里与std::array 的复杂性进行比较,我认为......假设transform 至少需要N 个op[]s(确实如此!)

标签: c++ functional-programming template-meta-programming random-access boost-hana


【解决方案1】:

运行时复杂度为 O(1)。基本上,它与访问结构成员一样快(因为它本质上就是这样)。实现类似于std::tuple

至于编译时间复杂度,也是 O(1),但您确实需要为开始创建元组支付 O(n) 编译时间复杂度。另外,在这里,我根据模板实例化的数量来衡量编译时复杂度,但这是衡量最终编译时间的一种非常幼稚的方法。

编辑:以下是元组访问工作原理的要点:

// Holds an element of the tuple
template <std::size_t n, typename Xn>
struct elt { Xn data_; };

// Inherits multiply from the holder structs
template <typename Indices, typename ...Xn>
struct tuple_impl;

template <std::size_t ...n, typename ...Xn>
struct tuple_impl<std::index_sequence<n...>, Xn...>
    : elt<n, Xn>...
{ /* ... */ };

template <typename ...Xn>
struct basic_tuple
    : tuple_impl<std::make_index_sequence<sizeof...(Xn)>, Xn...>
{ /* ... */ };

// When you call get<n>(tuple), your tuple is basically casted to a reference
// to one of its bases that holds a single element at the right index, and then
// that element is accessed.
template <std::size_t n, typename Xn>
Xn const& get(elt<n, Xn> const& xn)
{ return xn.data_; }

【讨论】:

  • 你能勾勒出 O(1) 编译时复杂度是如何实现的吗?我可以看到,对于固定长度的序列,您可以为每个元素(例如 get0get1、...、getn)实现一个访问器,以实现 O(1) 复杂度。但是如果在模板实例化之前知道长度,你怎么做呢?
  • 非常聪明!这部分有点棘手,你能澄清一下吗?当你打电话时get&lt;1&gt;(tuple) 编译器试图推断出第二个模板参数可能是什么,并且由于basic_tuple 仅继承自elt&lt;1, /* something */&gt; 类型的一类,那么Xn 被推断为/* something */
  • 这对吗?在名称查找期间,会考虑适当的get&lt;1, T&gt;,因为每个元组的基类都被添加到候选集中。然后在模板参数推导过程中只能选择一个,因为我们明确指定了n
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-19
  • 1970-01-01
  • 2018-11-24
相关资源
最近更新 更多