Open In App

C++ 20 – Ranges Library

Last Updated : 14 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

C++20 introduces the header, which presents a fresh method of handling ranges comprising arrays, vectors, or alternative data structures. With this header, you can take advantage of a set of standard algorithms that support activities like data filtering, transformation, and sorting. This approach enables you to perform such operations in a condensed and clear manner.

Declaration of Range of Library

#include <ranges>

Examples of Range Library

Example 1:

C++




// C++ Program to demonstrate the use of the <ranges>
// Header.
#include <iostream>
#include <ranges>
#include <vector>
  
int main()
{
    std::vector<int> nums = { 1, 2, 3, 4, 5 };
    auto even_nums = nums | std::views::filter([](int n) {
                         return n % 2 == 0;
                     });
    for (auto num : even_nums) {
        std::cout << num << " ";
    }
}


Output

2 4 

Explanation:

In the above example, Creating a vector of integers, we utilize the filter adaptor to produce a distinct range featuring solely the even digits. Afterward, employing a range-based for loop, we demonstrate the even digits on the console. To construct a range that only consists of even numbers, the nums range can be linked with the filter adaptor via the | operator. In this case, a lambda function that evaluates if an integer is even (i.e., its remainder is 0 when divided by 2) is passed to the filter.

Example 2:

C++




// C++ Program to demonstrate the use of the <ranges>
// Header.
#include <algorithm>
#include <iostream>
#include <ranges>
#include <string>
#include <vector>
using namespace std;
  
int main()
{
    vector<string> words
        = { "hello", "world", "c++", "ranges" };
    ranges::transform(
        words, words.begin(), [](std::string s) {
            transform(s.begin(), s.end(), s.begin(),
                           [](unsigned char c) {
                               return toupper(c);
                           });
            return s;
        });
    for (auto word : words) {
        std::cout << word << " ";
    }
}


Output

HELLO WORLD C++ RANGES

Explanation:

In the above example, our approach involves generating a string vector which we modify by converting each element to uppercase. In order to apply this transformation over the whole range rather than a single element, we employ std::ranges::transform instead of std::transform. The transformation of a string to an uppercase value utilizing std::transform is executed on a passed-by-value string within the lambda function for std::ranges::transform. The resulting outcome is returned as output.

Advantages of <ranges> Header

The advantages of using the <ranges> header are mentioned below:

  1. Range adaptors: The header comes with a variety of range adaptors, which are functions that change one range into a different one. One such example, the filter adaptor, takes a range and gives back a range that contains only the elements meeting a specific predicate. These range adaptors are beneficial because they make combining multiple transformations and filters into one expression as effortless as possible, freeing up time for developers to focus on other aspects of their code. Additionally, using range adaptors also enhances readability and reduces the amount of code duplication.
  2. Lazy evaluation: In the header, the algorithms leverage the lazy evaluation technique to handle the elements of a range only when required. Its application can drastically enhance performance, particularly when working on massive or intricate data structures.
  3. Type safety: By implementing templates and concepts, the header guarantees robust type security, allowing only compatible types to be utilized with algorithms and adaptors. This preventive measure at compile time effectively identifies and eliminates potential glitches that could otherwise disrupt program execution at runtime.
  4. Integration with standard library: The incorporation of the header into the standard library has ensured its smooth integration with the existing code, thereby reducing the complexity of usage. Additionally, users can leverage existing algorithms such as sort and partition, now compatible with ranges in place of iterators.
  5. Support for user-defined types: You can customize your own ranges and adaptors using the user-defined types that the header provides. This convenient feature lets you easily build bespoke data structures and algorithms that integrate smoothly with the standard library.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads