min element in vector c++
To find the minimum element in a vector in C++, you can use the std::min_element
function from the <algorithm>
library. Here are the steps to do so:
- Include the necessary headers:
#include <iostream>
#include <vector>
#include <algorithm>
- Declare and initialize a vector:
std::vector<int> numbers = {5, 2, 9, 1, 7};
- Use the
std::min_element
function to find the minimum element in the vector:
auto minElement = std::min_element(numbers.begin(), numbers.end());
The std::min_element
function returns an iterator pointing to the minimum element in the range specified by numbers.begin()
and numbers.end()
.
- Access the minimum element:
int minValue = *minElement;
To get the actual value of the minimum element, you need to dereference the iterator using the *
operator.
- Output the minimum element:
std::cout << "Minimum element: " << minValue << std::endl;
This will print the minimum element to the console.
Here's the complete code:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {5, 2, 9, 1, 7};
auto minElement = std::min_element(numbers.begin(), numbers.end());
int minValue = *minElement;
std::cout << "Minimum element: " << minValue << std::endl;
return 0;
}
When you run this code, it will output:
Minimum element: 1
This indicates that the minimum element in the vector numbers
is 1.