microsoft / microsoft/STL

`<algorithm>`: `ranges::sample` missing `difference_type` casting for `random_access_iterator` operations

Open
#2,886 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug ranges
Dominant language
C++
Stars
11.2k
Forks
1.7k
Avg merge
4d 15h
Merged PRs (30d)
22

Description

https://github.com/microsoft/STL/blob/ef62d3fa0b8e4e2406b9bb74e916e1ca8a1df802/stl/inc/algorithm#L4845-L4871

Although _Out is a random_access_iterator, it is only required to work on its own difference_type, not _It's difference_type.

Forgive me for the following nauseating test.

#include <algorithm>
#include <random>

struct I {
  using difference_type = long;
  using value_type = int;
  value_type& operator*() const;
  I& operator++();
  void operator++(int);
  bool operator==(std::default_sentinel_t) const;
};

struct O {
  using difference_type = int;
  using value_type = int;
  value_type& operator*() const;
  O& operator++();
  O operator++(int);
  O& operator--();
  O operator--(int);
  O& operator+=(difference_type);
  O& operator-=(difference_type);
  value_type& operator[](difference_type) const;
  friend O operator+(O, difference_type);
  friend O operator+(difference_type, O);
  friend O operator-(O, difference_type);
  friend difference_type operator-(O, O);
  auto operator<=>(const O&) const = default;

  friend O operator+(O, long) = delete;
};

int main() {
  std::ranges::sample(
    I{}, std::default_sentinel, O{}, 
    3, std::mt19937{std::random_device{}()});
}

https://godbolt.org/z/M8T94qhY1

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with stl/inc/algorithm at lines 4845-4871 and reproduce the issue using the custom iterator example in the report or its Godbolt link. Trace the ranges::sample random-access operations and verify that the supplied iterator types compile without requiring the output iterator to accept the input iterator's difference_type.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.