Preface
Range library for C++14/17/20. This code is the basis of the range support in C++20.
Development Status:
This code is fairly stable, well-tested, and suitable for casual use, although currently lacking documentation. No promise is made about support or long-term stability. This code will evolve without regard to backwards compatibility.
A notable exception is anything found within the ranges::cpp20 namespace. Those components will change rarely or (preferably) never at all.
Installation
This library is header-only. You can get the source code from the range-v3 repository on github. To compile with Range-v3, just #include the individual headers you want.
This distribution actually contains three separate header-only libraries:
- include/concepts/. contains the Concepts Portability Preprocessor, or CPP, which is a set of macros for defining and using concept checks, regardless of whether your compiler happens to support the C++20 concepts language feature or not.
- include/meta/. contains the Meta Library, which is a set of meta-programming utilities for processing types and lists of types at compile time.
- include/range/. contains the Range-v3 library, as described below.
The Range-v3 library is physically structured in directories by feature group:
- include/range/v3/actions/. contains actions, or composable components that operate eagerly on containers and return the mutated container for further actions.
- include/range/v3/algorithms/. contains all the STL algorithms with overloads that accept ranges, in addition to the familiar overloads that take iterators.
- include/range/v3/functional/. contains many generally useful components that would be familiar to functional programmers.
- include/range/v3/iterator/. contains the definitions of many useful iterators and iterator-related concepts and utilities.
- include/range/v3/numeric/. contains numeric algorithms corresponding to those found in the standard <numeric> header.
- include/range/v3/range/. contains range-related utilities, such as begin , end , and size , range traits and concepts, and conversions to containers.
- include/range/v3/utility/. contains a miscellaneous assortment of reusable code.
- include/range/v3/view/. contains views, or composable components that operate lazily on ranges and that themselves return ranges that can be operated upon with additional view adaptors.
License
Most of the source code in this project are mine, and those are under the Boost Software License. Parts are taken from Alex Stepanov’s Elements of Programming, Howard Hinnant’s libc++, and from the SGI STL. Please see the attached LICENSE file and the CREDITS file for the licensing and acknowledgements.
Supported Compilers
The code is known to work on the following compilers:
- clang 5.0
- GCC 6.5
- Clang/LLVM 6 (or later) on Windows
- MSVC VS2019, with /permissive- and either /std:c++latest , /std:c++20 , or /std:c++17
Quick Start
Range-v3 is a generic library that augments the existing standard library with facilities for working with ranges. A range can be loosely thought of a pair of iterators, although they need not be implemented that way. Bundling begin/end iterators into a single object brings several benefits: convenience, composability, and correctness.
Convenience
It’s more convenient to pass a single range object to an algorithm than separate begin/end iterators. Compare:
Range-v3 contains full implementations of all the standard algorithms with range-based overloads for convenience.
Composability
Having a single range object permits pipelines of operations. In a pipeline, a range is lazily adapted or eagerly mutated in some way, with the result immediately available for further adaptation or mutation. Lazy adaption is handled by views, and eager mutation is handled by actions.
For instance, the below uses views to filter a container using a predicate and transform the resulting range with a function. Note that the underlying data is const and is not mutated by the views.
In the code above, rng simply stores a reference to the underlying data and the filter and transformation functions. No work is done until rng is iterated.
In contrast, actions do their work eagerly, but they also compose. Consider the code below, which reads some data into a vector, sorts it, and makes it unique.
Unlike views, with actions each step in the pipeline ( actions::sort and actions::unique ) accepts a container by value, mutates it in place, and returns it.
Correctness
Whether you are using views or actions, you are operating on data in a pure functional, declarative style. You rarely need to trouble yourself with iterators, although they are there under the covers should you need them.
By operating declaratively and functionally instead of imperatively, we reduce the need for overt state manipulation and branches and loops. This brings down the number of states your program can be in, which brings down your bug counts.
In short, if you can find a way to express your solution as a composition of functional transformations on your data, you can make your code correct by construction.
Views
As described above, the big advantage of ranges over iterators is their composability. They permit a functional style of programming where data is manipulated by passing it through a series of combinators. In addition, the combinators can be lazy, only doing work when the answer is requested, and purely functional, without mutating the original data. This makes it easier to reason about your code.
A view is a lightweight wrapper that presents a view of an underlying sequence of elements in some custom way without mutating or copying it. Views are cheap to create and copy and have non-owning reference semantics. Below are some examples that use views:
Filter a container using a predicate and transform it.
Generate an infinite list of integers starting at 1, square them, take the first 10, and sum them:
Generate a sequence on the fly with a range comprehension and initialize a vector with it:
View const-ness
Logically, a view is a factory for iterators, but in practice a view is often implemented as a state machine, with the state stored within the view object itself (to keep iterators small) and mutated as the view is iterated. Because the view contains mutable state, many views lack a const -qualified begin() / end() . When const versions of begin() / end() are provided, they are truly const ; that is, thread-safe.
Since views present the same interface as containers, the temptation is to think they behave like containers with regard to const -ness. This is not the case. Their behavior with regards to const -ness is similar to iterators and pointers.
The const -ness of a view is not related to the const -ness of the underlying data. A non- const view may refer to elements that are themselves const , and vice versa. This is analogous to pointers; an int* const is a const pointer to a mutable int , and a int const* is a non- const pointer to a const int .
Use non- const views whenever possible. If you need thread-safety, work with view copies in threads; don’t share.
View validity
Any operation on the underlying range that invalidates its iterators or sentinels will also invalidate any view that refers to any part of that range. Additionally, some views (e.g., views::filter ), are invalidated when the underlying elements of the range are mutated. It is best to recreate a view after any operation that may have mutated the underlying range.
List of range views
Below is a list of the lazy range combinators, or views, that Range-v3 provides, and a blurb about how each is intended to be used.
views::addressof Given a source range of lvalue references, return a new view that is the result of taking std::addressof of each. views::adjacent_filter For each pair of adjacent elements in a source range, evaluate the specified binary predicate. If the predicate evaluates to false, the second element of the pair is removed from the result range; otherwise, it is included. The first element in the source range is always included. (For instance, adjacent_filter with std::not_equal_to filters out all the non-unique elements.) views::adjacent_remove_if For each pair of adjacent elements in a source range, evaluate the specified binary predicate. If the predicate evaluates to true, the first element of the pair is removed from the result range; otherwise, it is included. The last element in the source range is always included. views::all Return a range containing all the elements in the source. Useful for converting containers to ranges. any_view<T>(rng) Type-erased range of elements with value type T ; can store any range with this value type. views::c_str View a \0 -terminated C string (e.g. from a const char* ) as a range. views::cache1 Caches the most recent element within the view so that dereferencing the view’s iterator multiple times doesn’t incur any recomputation. This can be useful in adaptor pipelines that include combinations of view::filter and view::transform , for instance. views::cache1 is always single-pass. views::cartesian_product Enumerates the n-ary cartesian product of n ranges, i.e., generates all n -tuples (e1, e2, . , en) where e1 is an element of the first range, e2 is an element of the second range, etc. views::chunk Given a source range and an integer N, produce a range of contiguous ranges where each inner range has N contiguous elements. The final range may have fewer than N elements. views::common Convert the source range to a common range, where the type of the end is the same as the begin . Useful for calling algorithms in the std:: namespace. views::concat Given N source ranges, produce a result range that is the concatenation of all of them. views::const_ Present a const view of a source range. views::counted Given an iterator it and a count n , create a range that starts at it and includes the next n elements. views::cycle Returns an infinite range that endlessly repeats the source range. views::delimit Given a source range and a value, return a new range that ends either at the end of the source or at the first occurrence of the value, whichever comes first. Alternatively, views::delimit can be called with an iterator and a value, in which case it returns a range that starts at the specified position and ends at the first occurrence of the value. views::drop Given a source range and an integral count, return a range consisting of all but the first count elements from the source range, or an empty range if it has fewer elements. views::drop_last Given a source range and an integral count, return a range consisting of all but the last count elements from the source range, or an empty range if it has fewer elements. views::drop_exactly Given a source range and an integral count, return a range consisting of all but the first count elements from the source range. The source range must have at least that many elements. views::drop_while Remove elements from the front of a range that satisfy a unary predicate. views::empty Create an empty range with a given value type. views::enumerate Pair each element of a range with its index. views::filter Given a source range and a unary predicate, filter the elements that satisfy the predicate. (For users of Boost.Range, this is like the filter adaptor.) views::for_each Lazily applies an unary function to each element in the source range that returns another range (possibly empty), flattening the result. views::generate Given a nullary function, return an infinite range whose elements are generated with the function. views::generate_n Given a nullary function and a count, return a range that generates the requested number of elements by calling the function. views::chunk_by Given a source range and a binary predicate, return a range of ranges where each range contains contiguous elements from the source range such that the following condition holds: for each element in the range apart from the first, when that element and the previous element are passed to the binary predicate, the result is true. In essence, views::chunk_by groups contiguous elements together with a binary predicate. views::indirect Given a source range of readable values (e.g. pointers or iterators), return a new view that is the result of dereferencing each. views::intersperse Given a source range and a value, return a new range where the value is inserted between contiguous elements from the source. views::ints Generate a range of monotonically increasing int s. When used without arguments, it generates the quasi-infinite range [0,1,2,3. ]. It can also be called with a lower bound, or with a lower and upper bound (exclusive). An inclusive version is provided by closed_ints . views::iota A generalization of views::ints that generates a sequence of monotonically increasing values of any incrementable type. When specified with a single argument, the result is an infinite range beginning at the specified value. With two arguments, the values are assumed to denote a half-open range. views::join Given a range of ranges, join them into a flattened sequence of elements. Optionally, you can specify a value or a range to be inserted between each source range. views::keys Given a range of pair s (like a std::map ), return a new range consisting of just the first element of the pair . views::linear_distribute Distributes n values linearly in the closed interval [from, to] (the end points are always included). If from == to , returns n -times to , and if n == 1 it returns to . views::move Given a source range, return a new range where each element has been cast to an rvalue reference. views::partial_sum Given a range and a binary function, return a new range where the N th element is the result of applying the function to the N th element from the source range and the (N-1)th element from the result range. views::remove Given a source range and a value, filter out those elements that do not equal value. views::remove_if Given a source range and a unary predicate, filter out those elements that do not satisfy the predicate. (For users of Boost.Range, this is like the filter adaptor with the predicate negated.) views::repeat Given a value, create a range that is that value repeated infinitely. views::repeat_n Given a value and a count, create a range that is that value repeated count number of times. views::replace Given a source range, a source value and a target value, create a new range where all elements equal to the source value are replaced with the target value. views::replace_if Given a source range, a unary predicate and a target value, create a new range where all elements that satisfy the predicate are replaced with the target value. views::reverse Create a new range that traverses the source range in reverse order. views::sample Returns a random sample of a range of length size(range) . views::single Given a value, create a range with exactly one element. views::slice Give a source range a lower bound (inclusive) and an upper bound (exclusive), create a new range that begins and ends at the specified offsets. Both the begin and the end can be integers relative to the front, or relative to the end with «`end-2`» syntax. views::sliding Given a range and a count n , place a window over the first n elements of the underlying range. Return the contents of that window as the first element of the adapted range, then slide the window forward one element at a time until hitting the end of the underlying range. views::split Given a source range and a delimiter specifier, split the source range into a range of ranges using the delimiter specifier to find the boundaries. The delimiter specifier can be an element or a range of elements. The elements matching the delimiter are excluded from the resulting range of ranges. views::split_when Given a source range and a delimiter specifier, split the source range into a range of ranges using the delimiter specifier to find the boundaries. The delimiter specifier can be a predicate or a function. The predicate should take a single argument of the range’s reference type and return true if and only if the element is part of a delimiter. The function should accept an iterator and sentinel indicating the current position and end of the source range and return std::make_pair(true, iterator_past_the_delimiter) if the current position is a boundary; otherwise std::make_pair(false, ignored_iterator_value) . The elements matching the delimiter are excluded from the resulting range of ranges. views::stride Given a source range and an integral stride value, return a range consisting of every N th element, starting with the first. views::tail Given a source range, return a new range without the first element. The range must have at least one element. views::take Given a source range and an integral count, return a range consisting of the first count elements from the source range, or the complete range if it has fewer elements. (The result of views::take is not a sized_range .) views::take_exactly Given a source range and an integral count, return a range consisting of the first count elements from the source range. The source range must have at least that many elements. (The result of views::take_exactly is a sized_range .) views::take_last Given a source range and an integral count, return a range consisting of the last count elements from the source range. The source range must be a sized_range . If the source range does not have at least count elements, the full range is returned. views::take_while Given a source range and a unary predicate, return a new range consisting of the elements from the front that satisfy the predicate. views::tokenize Given a source range and optionally a submatch specifier and a std::regex_constants::match_flag_type , return a std::regex_token_iterator to step through the regex submatches of the source range. The submatch specifier may be either a plain int , a std::vector<int> , or a std::initializer_list<int> . views::transform Given a source range and a unary function, return a new range where each result element is the result of applying the unary function to a source element. views::trim Given a source bidirectional range and a unary predicate, return a new range without the front and back elements that satisfy the predicate. views::unbounded Given an iterator, return an infinite range that begins at that position. views::unique Given a range, return a new range where all consecutive elements that compare equal save the first have been filtered out. views::values Given a range of pair s (like a std::map ), return a new range consisting of just the second element of the pair . views::zip Given N ranges, return a new range where M th element is the result of calling make_tuple on the M th elements of all N ranges. views::zip_with Given N ranges and a N-ary function, return a new range where M th element is the result of calling the function on the M th elements of all N ranges.
Actions
When you want to mutate a container in-place, or forward it through a chain of mutating operations, you can use actions. The following examples should make it clear.
Создать диапазон чисел в C++
мне нужна помощь в определении диапазона чисел. У меня ошибка в коде и результат выглядит так:
Input: rangeStart = 1, rangeEnd = 23, periodLength = 10
Output: 1 2 3 4 5 6 7 8 9 10 11-20 21 22 23
Мне нужно, чтобы это было:
Input: rangeStart = 1, rangeEnd = 23, periodLength = 10
Output: 1-10 11-20 21 22 23
Буду признателен за любой ответ
![]()
Лишние вызовы функций, создание объектов и арифметические действия, тормозят программу.Часто лучше просто генерировать числа с заданным шагом и стартовым значением, пока не достигли конца. Представлю вариант:
![]()
Чисто исходя из ваших примеров ввода вывода:
В вашем коде вы на первой итерации получаете 1 и выписываете весь период, а после периода вы прибавляете слишком много и снова выписываете полный период. Это более заметно если rangeEnd взять большой.
И, возможно, вам будет лучше использовать enum для periodType .
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.9.7.43618
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Полный гайд по созданию диапазона чисел в C#: от начала до конца
C# – это язык программирования, который предоставляет множество возможностей для работы с числами и диапазонами чисел. Если вы хотите научиться создавать диапазоны чисел в C#, тогда в этой статье вы найдете подробные инструкции и примеры.
Определение диапазона чисел
Диапазон чисел представляет собой набор чисел, которые находятся между начальным и конечным значениями, включая эти значения. Существует несколько способов создания диапазона чисел в C#.
Использование цикла for для создания диапазона чисел
Один из наиболее распространенных способов создания диапазона чисел – использовать цикл for.
В этом примере startValue – это начальное значение, а endValue – это конечное значение диапазона. Цикл for создает все значения между начальным и конечным значениями, включая эти значения.
Использование класса Enumerable для создания диапазона чисел
Еще один способ создания диапазона чисел – использовать класс Enumerable.
В этом примере startValue – это начальное значение, а endValue – это конечное значение диапазона. Метод Range класса Enumerable создает диапазон чисел со всеми значениями между начальным и конечным значениями, включая эти значения.
Использование LINQ для создания диапазона чисел
Еще один способ создать диапазон чисел – использовать Language-Integrated Query (LINQ).
В этом примере startValue – это начальное значение, а endValue – это конечное значение диапазона. Метод Range класса Enumerable создает диапазон чисел со всеми значениями между начальным и конечным значениями, включая эти значения. Затем метод LINQ select используется для выбора каждого числа в диапазоне.
Заключение
Теперь, когда вы знаете, как создавать диапазоны чисел в C#, вы можете использовать эту информацию для упрощения работы с большими количествами чисел в ваших проектах. Также помните, что C# предоставляет множество других возможностей для работы с числами: от математических операций до форматирования чисел.
Диапазоны (Ranges) в C# 8
Пусть в нашей программе есть массив целых чисел numbers :
Перед нами стоит задача: получить новый массив, вырезав из массива numbers элементы от индекса 2 до индекса 4 включительно, то есть должен получится массив [4, 2, 3] .
Решение 1
Самое первое и простое решение, которое приходит в голову — это решение в лоб:
Создадим результирующий массив целых чисел result размером 3 :
Пройдемся циклом по нужным индексам массива numbers , а именно с 2 до 4 включительно:
Запишем в результирующий массив result нужные значения:
Выведем массив result и убедимся, что все ОК:
С задачей мы справились. Но есть некоторые недостатки:
Для решения такой маленькой задачи, пришлось пройтись циклом.
По коду не сразу понятно, что он делает. Таким образом страдает читаемость.
Также можно ошибиться с индексами (относится к начинающим программистам).
Следовательно, такое решение нас не устраивает.
Решение 2
Немногие знают, что у списка ( List ) есть готовый метод GetRange(int index, int count) , который получает из списка нужный диапазон элементов. Метод первым параметром принимает index — индекс начала диапазона, а вторым параметром count — количество элементов, которые нужно получить. Например:
GetRange(0, 5) — получает 5 элементов, начиная с индекса 0.
GetRange(3, 10) — получает 10 элементов, начиная с индекса 3.
Тогда сделаем следующее:
Для того чтобы мы воспользовались готовым методом GetRange , преобразуем массив в список с помощью метода ToList :
Воспользуемся методом GetRange . Нам нужно взять 3 элемента, начиная с индекса 2 :
Метод GetRange вернул результат в виде списка ( List<int> ). Для того чтобы преобразовать его в массив, воспользуемся методом ToArray :
Выведем массив result и убедимся, что все ОК:
С задачей мы справились. Но есть некоторые недостатки:
Для решения такой маленькой задачи, пришлось воспользоваться тремя дополнительными методами.
По коду не сразу понятно, что он делает. Таким образом страдает читаемость.
Также можно ошибиться при передаче параметров в метод GetRange (относится к начинающим программистам).
Данные преобразования ресурсоемкие по памяти и производительности. Вызовы ToList , ToArray проходятся по коллекции и выделяют новую память.
Следовательно, такое решение нас не устраивает.
Решение 3
Можно еще воспользоваться технологией LINQ , а именно двумя методами:
Skip(int count) — возвращает все элементы коллекции, кроме первых count .
Take(int count) — возвращает первые count элементов коллекции.
В нашем случае, для того, чтобы взять элементы массива от индекса 2 до индекса 4 включительно, нужно пропустить 2 элемента последовательности, а затем взять первые 3 элемента. Как раз получатся элементы с индексами от 2 до 4 .
Посмотрим в коде:
С задачей мы справились. Но есть некоторые недостатки:
Для решения такой маленькой задачи, пришлось воспользоваться тремя дополнительными методами.
Можно ошибиться при передаче параметров в методы Skip и Take (относится к начинающим программистам).
Данные преобразования ресурсоемкие по памяти и производительности.
Следовательно, такое решение нас не устраивает.
Решение 4
Есть еще статический метод Copy у класса Array :
Данный метод копирует элементы из одного массива в другой. Давайте поясним каждый параметр:
Array sourceArray — массив, с которого копируем элементы.
int sourceIndex — с какого индекса из массива sourceArray начинаем копировать элементы.
Array destinationArray — массив, в который копируются элементы.
int destinationIndex — начиная с какого индекса в результирующем массиве destinationArray вставляются элементы.
int length — количество элементов, которое нужно скопировать.
Давайте воспользуемся данным методом:
Создадим результирующий массив целых чисел result размером 3 :
Вызываем метод Copy . Передаем массив numbers и индекс 2 — откуда начинаем вырезать элементы. Затем передаем результирующий массив result и индекс 0 — с какого индекса вставляются элементы. А затем передаем 3 — количество элементов, которое нужно скопировать:
Выведем массив result и убедимся, что все ОК:
С задачей мы справились. Но есть некоторые недостатки:
Легко можно ошибиться при передаче параметров в метод Copy (относится к начинающим программистам).
Не сразу понятно как использовать метод Copy , ведь он ничего не возвращает. Нужно понять, что результат возвращается в массиве, который был передан третьим параметром.
Следовательно, такое решение нас не устраивает.
Решение 5
В C# 8 версии добавили дополнительную функциональность для работы с диапазонами ( Range ). Теперь для решения нашей задачи можно написать вот так:
То есть, для того чтобы получить некоторый диапазон из коллекции, нужно в квадратных скобках указать начальный индекс, затем .. и наконец индекс конца (. НЕ включительно . ).
numbers[3..10] — вырезает элементы, начиная с индекса 3 и заканчивая индексом 9 . Напоминаю, что правая граница не включается.
numbers[1..7] — вырезает элементы, начиная с индекса 1 и заканчивая индексом 6 .
Если индексы будут равны между собой, то в результате получится массив нулевой длины:
Если первый индекс будет больше второго индекса, то возникнет исключение ArgumentOutOfRangeException во время выполнения программы:
Можно использовать также индексацию справа налево ( Indices ), введенную тоже в C# 8 версии, про которую говорили совсем недавно:
Можно делать еще более веселые штучки:
Например, для получения первых n элементов с помощью диапазонов, нужно написать numbers[0..n] . Так вот, специально для случаев, когда вы хотите взять диапазон с начала массива (когда первый индекс равен 0 ), придумали упрощение: можно индекс равный 0 опускать, то есть написать вот так: numbers[..n] . Такая запись более предпочтительна.
Например, для получения всех элементов, кроме первых n с помощью диапазонов, нужно написать numbers[n..numbers.Length] . Специально для случаев, когда вы хотите взять все элементы, кроме первых n (начиная с индекса n и до конца массива), придумали упрощение. Так как второй индекс всегда равен длине массива, то его можно опустить, то есть написать вот так: numbers[n..] . Такая запись более предпочтительна.
Ну и комбинация этих двух подходов. Для получения полной копии массива, можно написать вот так: numbers[..] , то есть опустить оба индекса. Это означает взять диапазон от начала массива до конца.
Что там под капотом?
На самом деле любой диапазон в C# 8 версии можно хранить в новом типе данных Range . Он находится в пространстве имен ( namespace ) System , следовательно, никакой дополнительный using при его использовании не нужно писать.
У Range существует два конструктора:
Range() – создает пустой диапазон.
Range(Index start, Index end) – создает диапазон от индекса start (включительно) и до индекса end (НЕ включительно).
Рассмотрим на примерах:
Заметьте, что объект типа Range передается в качестве индекса в квадратные скобки ( [] ).
Проведем соответствие между двумя разными записями:
Укороченная версия
Версия с Range
numbers[new Range(2, 5)]
numbers[new Range(^6, ^2)]
В Range реализовано неявное преобразование укороченной записи (например 2..5 ) к Range . Вот как это работает:
У Range переопределен метод Equals :
А можно вообще вот так:
Здесь сначала происходит неявное преобразование укороченной записи к Range , а потом вызов Equals .
У Range переопределен также метод ToString :
Заметьте, что для индексации с конца выводится ^ перед индексом.
Также теперь мы можем в методы передавать диапазон:
Выводы:
Структура Range позволяет создать экземпляр, к которому можно обращаться многократно.