How to find min element using std::ranges::min in c++?

by aglae_feil , in category: General Help , 2 months ago

How to find min element using std::ranges::min in c++?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by enrico , 2 months ago

@aglae_feil 

To find the minimum element using std::ranges::min in C++, you need to include the <algorithm> and <ranges> header files.


Here's an example of how to use std::ranges::min:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>

int main() {
    // Create a vector of integers
    std::vector<int> numbers = {4, 2, 6, 1, 5};

    // Find the minimum element using std::ranges::min
    auto minElement = std::ranges::min(numbers);

    // Print the minimum element
    std::cout << "Minimum element: " << *minElement << std::endl;

    return 0;
}


In this example, we have a vector of integers called numbers. We use std::ranges::min to find the minimum element in the numbers vector and store the iterator pointing to that element in the minElement variable. Finally, we print the minimum element by dereferencing the iterator.


The output of this code will be:

1
Minimum element: 1