folly::range_has_known_distance_v

Whether std::distance over the begin and end iterators is reasonably known to give the distance without advancing the iterators or copies of them.

Synopsis

Declared in <folly/container/Iterator.h>

template<typename Range>
inline constexpr bool range_has_known_distance_v = iterator_has_known_distance_v<
        invoke_result_t<access::begin_fn, Range>,
        invoke_result_t<access::end_fn, Range>>;

Description

Useful for conditionally reserving memory in advance of iterating the range.

Note: Many use-cases are better served by range-v3 or std::ranges.

Example:

std::vector<result_type> results; auto elems = /* some range */; auto const elemsb = folly::access::begin(elems); auto const elemse = folly::access::end(elems);

if constexpr (range_has_known_distance_v<decltype(elems)>) { auto const dist = std::distance(elemsb, elemse); results.reserve(static_cast<std::size_t>(dist)); }

for (auto elemsi = elemsb; elemsi != elemsi; ++i) { results.push_back(do_work(*elemsi)); } return results;