C++ Ranges

 C++ Ranges


Ranges are a new feature introduced in C++20 that provide a way to operate on sequences of values. They allow for concise and expressive code when working with collections. Here's an example using ranges to filter and print even numbers:


#include <iostream>

#include <vector>

#include <ranges>


int main() {

    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};


    // Filtering and printing even numbers

    auto evenNumbers = numbers | std::views::filter([](int x) {

        return x % 2 == 0;

    });


    for (int num : evenNumbers) {

        std::cout << num << " ";

    }

    std::cout << std::endl;


    return 0;

}

In the above code, we define a vector numbers with some integers. Using ranges, we create a filtered range of even numbers by applying the filter view on the numbers vector. We provide a lambda function to determine if a number is even or not. Finally, we iterate over the evenNumbers range and print each element.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...