max element in vector c++
Code to Find the Maximum Element in a Vector in C++
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
int max_element = *std::max_element(vec.begin(), vec.end());
std::cout << "The maximum element in the vector is: " << max_element << std::endl;
return 0;
}
- Include Necessary Libraries:
#include <iostream>
: This library is included for input and output operations.#include <vector>
: This library is included to use the vector class.#include <algorithm>
: This library is included to use thestd::max_element
function.Main Function:
int main() { ... }
: The main function serves as the entry point for the program.Create Vector:
std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
: A vector of integers namedvec
is created and initialized with some values.Find Maximum Element:
int max_element = *std::max_element(vec.begin(), vec.end());
: Thestd::max_element
function is used to find the maximum element in the vector. The result is stored in the variablemax_element
.Output Result:
std::cout << "The maximum element in the vector is: " << max_element << std::endl;
: The maximum element found is printed to the console.Return Statement:
return 0;
: The program exits with a return value of 0, indicating successful execution.