C++ Ranges::all_view, begin, cbegin Introduction














































C++ Ranges::all_view, begin, cbegin Introduction




  • In this series of articles on RANGES with C++, today we are going to see libraries of std::ranges::all_view , std::ranges::begin and std::ranges::cbegin.
____________________________________________________________________________________

Introduction to RANGES Library

  • A range is a group of items that we can iterator over.
  •  It provides a begin iterator and an end iterator.
Hence,

  • The ranges library provides tools for dealing with ranges of elements, including few view adapters.
  • Views specifies that a range has a constant time copy,move and assignment functions/operators.
  • A view does not own data and it's time to copy, move, assignment its constant.


To use the ranges library we can use the online compiler Wandbox or the Compiler Explorer with the HEAD GCC.


All the libraries defined below are included in the header <ranger> and <iterator>.


std::ranges::all_view


A view (which returns an iterator) that includes all the elements in the range defined.


Sample Code

#include <ranges>
#include <vector>
#include <iostream>
 
int main()
{
    std::vector<int> v = {32, 21, 3232, 11, 1 };
for(int n : std::views::all(v) | std::views::take(4) ) { std::cout << n << ' '; } }

Output

32 21 3232 11


std::ranges::begin


 It returns an iterator to the first element of the argument.

 

Sample Code


#include <iostream>
#include <vector>
#include <ranges>
 
int main() 
{
    std::vector<int> v = { 32, 21, 3232, 11, 1 };
    auto beg = std::ranges::begin(v);
    std::cout << *beg << '\n';
}

Output

32

std::ranges::cbegin.

 It returns an iterator to the beginning of read only range.

Sample Code


#include <iostream>
#include <vector>
#include <ranges>
 
int main() 
{
    std::vector<int> v = { 32, 21, 3232, 11, 1 };
    auto cbeg = std::ranges::cbegin(v);
    std::cout << *cbeg << '\n';
    *cbeg= 12  // here it shows an error as it only read only.
}

Output

32



Comments