Skip to content

Ranges library (C++20)

首先搞清楚C++20为什么引入range library。

What's new in C++

在C++20之前,C++中也是由range的概念的: "begin, end",后面为了区分,使用"begin, end"来表示;C++20前的algorithm都是基于"begin, end"的;

C++20其,C++引入了ranges library,显然它是显式对对range的定义 ,它的引入重要是为了解决iterator的问题。

wikipedia Standard Template Library

The concept of iterators as implemented by STL can be difficult to understand at first: for example, if a value pointed to by the iterator is deleted, the iterator itself is then no longer valid. This is a common source of errors. Most implementations of the STL provide a debug mode that is slower, but can locate such errors if used. A similar problem exists in other languages, for example Java.

Ranges have been proposed as a safer, more flexible alternative to iterators.

显然,基于range的generic programming有着一些优势,本章对range的一些内容进行梳理。

wikipedia Range as an alternative to iterator

Another meaning of range in computer science is an alternative to iterator. When used in this sense, range is defined as "a pair of begin/end iterators packed together".[1] It is argued [1] that "Ranges are a superior abstraction" (compared to iterators) for several reasons, including better safety.

In particular, such ranges are supported in Boost C++ Libraries[2] and the D standard library.[3]

Andrei Alexandrescu Iterators Must Go

Range is an abstraction as iterator be

和iterator类似,range也是一种抽象,它是**behavior-defined**(参见Theory\Programming-paradigm\Generic-programming\Templates-and-Duck-Typing\Templates-and-Duck-Typing.md),只要支持beginend、iteration操作,那么就可以作为range,这就包括了c++的各种容器,正如cppreference Range-based for loop中所述:

Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.

Range is an enhancement to iterator

range是对iterator的增强,两者都旨在generic programming。

cppreference Ranges library (C++20)

boost Boost range

cppreference Ranges library (C++20)

The ranges library provides components for dealing with ranges of elements, including a variety of view adapters.