【问题标题】:Does the output sequence of `std::sample()` follow the order of the input sequence?`std::sample()` 的输出序列是否遵循输入序列的顺序?
【发布时间】:2019-02-20 04:06:25
【问题描述】:

std::sample()的输出序列是否遵循输入序列的顺序?

例如,

const std::vector<int> input{2, 4, 6, 8, 1, 3, 5, 7};
std::vector<int> output;
std::sample(input.begin(), input.end(), std::back_inserter(output), 3, any_urbg);

是否保证output 永远不可能成为[1, 2, 3]

【问题讨论】:

    标签: c++ algorithm random c++17


    【解决方案1】:

    std::sample 上的引用说明:

    仅当 PopulationIterator 满足 LegacyForwardIterator

    的要求时,该算法是稳定的(保留所选元素的相对顺序

    PopulationIterator 这里是std::vector 的迭代器。 std::vector 的迭代器是一个LegacyRandomAccessIterator,它满足LegacyBidirectionalIterator 的类型,而LegacyBidirectionalIterator 又满足LegacyForwardIterator 的类型。

    所以,是的,保证输出永远不可能是[1, 2, 3],因为这会违反所选元素的相对顺序,即[2, 1, 3]

    【讨论】:

      【解决方案2】:

      来自std::sample

      只有当 PopulationIterator 满足 LegacyForwardIterator 的要求时,算法才是稳定的(保留被选元素的相对顺序)

      【讨论】:

        【解决方案3】:

        根据https://en.cppreference.com/w/cpp/algorithm/sample

        只有PopulationIterator满足LegacyForwardIterator的要求,算法才是稳定的(保留被选元素的相对顺序)

        在你的例子中,PopulationIteratorstd::vector&lt;int&gt;::iterator,这确实是一个 LegacyForwardIterator(实际上是一个 LegacyRandomAccessIterator),所以,是的,元素output 中的元素应该与 input 中的元素相同。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-06-18
          • 1970-01-01
          • 2017-05-28
          • 2017-02-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多