Improved Iterators with Ranges

Contents[Show]

There are more reasons to prefer ranges library above the classical Standard Template Library. The ranges iterators support unified lookup rules and provide additional safety guarantees.

 TimelineCpp20

Unified Lookup Rules

Assume you want to implement a generic function that calls begin on a given container. The question is if the function calling begin on a container should assume a free begin function or a member function begin?

 

// begin.cpp

#include <cstddef>
#include <iostream>
#include <ranges>

struct ContainerFree {                                        // (1)
    ContainerFree(std::size_t len): len_(len), data_(new int[len]){}
    size_t len_;
    int* data_;
};
int* begin(const ContainerFree& conFree) {                   // (2)
    return conFree.data_;
}

struct ContainerMember {                                     // (3)
    ContainerMember(std::size_t len): len_(len), data_(new int[len]){}
    int* begin() const {                                     // (4)
        return data_;
    }
    size_t len_;
    int* data_;
};

void callBeginFree(const auto& cont) {                        // (5)
    begin(cont);
}

void callBeginMember(const auto& cont) {                      // (6)
    cont.begin();
}
 
int main() {

    const ContainerFree contFree(2020);
    const ContainerMember contMemb(2023);

    callBeginFree(contFree);                                 
    callBeginMember(contMemb);

    callBeginFree(contMemb);                                  // (7)
    callBeginMember(contFree);                                // (8)
   
}

 

ContainerFree (line 1) has a free function begin (line 2), and ContainerMember (line 3) has a member function begin (line 4). Accordingly, contFree can use the generic function callBeginFree using the free function call begin(cont) (line 5), and contMemb can use the generic function callBeginMember using the member function call cont.begin (line 6). When I invoke callBeginFree and callBeginMember with the inappropriate containers in lines (7) and (8), the compilation fails.
begin

I can solve this issue by providing two different begin implementations in two ways: classical and range based.

 

// beginSolved.cpp

#include <cstddef>
#include <iostream>
#include <ranges>

struct ContainerFree {
    ContainerFree(std::size_t len): len_(len), data_(new int[len]){}
    size_t len_;
    int* data_;
};
int* begin(const ContainerFree& conFree) {
    return conFree.data_;
}

struct ContainerMember {
    ContainerMember(std::size_t len): len_(len), data_(new int[len]){}
    int* begin() const {
        return data_;
    }
    size_t len_;
    int* data_;
};

void callBeginClassical(const auto& cont) {
    using std::begin;                          // (1)
    begin(cont);
}

void callBeginRanges(const auto& cont) {
    std::ranges::begin(cont);                  // (2)
}
 
int main() {

    const ContainerFree contFree(2020);
    const ContainerMember contMemb(2023);

    callBeginClassical(contFree);
    callBeginRanges(contMemb);

    callBeginClassical(contMemb);
    callBeginRanges(contFree);
   
}

 

The classical way to solve this issue is to bring std::begin into the scope with a so-called using declaration (line 1). Thanks to ranges, you can directly use std::ranges::begin (line 2). std::ranges::begin considers both implementations of begin: the free version and the member function.

Finally, let me write about safety.

Safety

Let me start with iterators.

Iterators

The ranges library provides the expected operations to access the range.
 
 iterators

 

When you use these operations for accessing the underlying range, there is a big difference. The compilation fails when you use the range access on the std::ranges's variant if the argument is an rvalue. On the contrary, using the same operation from the classical std namespace is undefined behavior.

// rangesAccess.cpp

#include <iterator>
#include <ranges>
#include <vector>

int main() {

    auto beginIt1 = std::begin(std::vector<int>{1, 2, 3});
    auto beginIt2 = std::ranges::begin(std::vector<int>{1, 2, 3});

}

 

std::ranges::begin provides only overloads for lvalues. The temporary vector std::vector{1, 2, 3} is an rvalue. Consequentially, the compilation of the program fails.

rangeAccessError

The abbreviations lvalue and rvalue stand for locatable value and readable value.

  • lvalue (locatable value): A locatable value is an object that has a location in memory, and you can, therefore, determine its address. An lvalue has an identity.
  • rvalue (readable value): A rvalue is a value you can only read from. It does not represent an object in memory, and you cannot determine its address.

I have to admit to you that my short explanations of lvalues and rvalues is a simplification. If you want to know more details about value categories, read the following post Value Categories.

By the way, not only iterators but also views provide these additional safety guarantees.

Views

Views do not own data. Therefore, views do not extend the lifetime of their data. Consequently, views can only be created on lvalues. The compilation fails if you create a view on a temporary range.

// temporaryRange.cpp

#include <initializer_list>
#include <ranges>


int main() {

    const auto numbers = {1, 2, 3, 4, 5};

    auto firstThree = numbers | std::views::drop(3);             // (1)
    // auto firstThree = {1, 2, 3, 4, 5} | std::views::drop(3);  // (2)

    std::ranges::drop_view firstFour{numbers, 4};                // (3)
   // std::ranges::drop_view firstFour{{1, 2, 3, 4, 5}, 4};      // (4)
   
}

 

When lines 1 and 3 are used with the lvalue numbers, all is fine. On the contrary, using the commented-out lines 2 and 4 on the rvalue std::initializer_list<int> {1, 2, 3, 4, 5}, causes the GCC compiler to complain verbosely:

temporaryRange

What's next?

In my next post, I do my first peek into the C++23 future. In particular, the ranges library will get many improvements. There is with std::ranges::to a convenient way to construct containers from ranges. Additionally, we will get almost twenty new algorithms. Here are a few of them: std::views::chunk_by, std::views::slide, std::views::join_with, std::views::zip_transform, and std::views::adjacent_transform.

 

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Ralf Holly, Juan Dent, George Liao, Daniel Ceperley, and Jon T Hess.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, Ralf Abramowitsch, John Nebel, and Mipko.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

Mentoring Program in English

Do you want to stay informed about my mentoring programs? Write to This email address is being protected from spambots. You need JavaScript enabled to view it..

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

New

Contact Me

Modernes C++,

RainerGrimmSmall

My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 783

Yesterday 6750

Week 15120

Month 235956

All 9709588

Currently are 163 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments