minimum and maximum value of a vector in C++

To find the minimum and maximum values of a vector in C++, you can use the min_element and max_element functions from the <algorithm> header. Here's how you can do it:

  1. Include the necessary header: cpp #include <algorithm>

  2. Create a vector and populate it with values: cpp std::vector<int> numbers = {5, 2, 9, 1, 7};

  3. Use the min_element and max_element functions to find the minimum and maximum values respectively: cpp auto min = std::min_element(numbers.begin(), numbers.end()); auto max = std::max_element(numbers.begin(), numbers.end());

  4. Access the values by dereferencing the iterators: cpp int minValue = *min; int maxValue = *max;

The min_element function returns an iterator pointing to the smallest element in the given range, while the max_element function returns an iterator pointing to the largest element in the range. By dereferencing these iterators, you can obtain the actual minimum and maximum values from the vector.

Here's the complete code example:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> numbers = {5, 2, 9, 1, 7};

    auto min = std::min_element(numbers.begin(), numbers.end());
    auto max = std::max_element(numbers.begin(), numbers.end());

    int minValue = *min;
    int maxValue = *max;

    std::cout << "Minimum value: " << minValue << std::endl;
    std::cout << "Maximum value: " << maxValue << std::endl;

    return 0;
}

Output:

Minimum value: 1
Maximum value: 9

Note: The min_element and max_element functions return iterators, so if the vector is empty, you need to handle that case separately to avoid undefined behavior.