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;
}
  1. Include Necessary Libraries:
  2. #include <iostream>: This library is included for input and output operations.
  3. #include <vector>: This library is included to use the vector class.
  4. #include <algorithm>: This library is included to use the std::max_element function.

  5. Main Function:

  6. int main() { ... }: The main function serves as the entry point for the program.

  7. Create Vector:

  8. std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};: A vector of integers named vec is created and initialized with some values.

  9. Find Maximum Element:

  10. int max_element = *std::max_element(vec.begin(), vec.end());: The std::max_element function is used to find the maximum element in the vector. The result is stored in the variable max_element.

  11. Output Result:

  12. std::cout << "The maximum element in the vector is: " << max_element << std::endl;: The maximum element found is printed to the console.

  13. Return Statement:

  14. return 0;: The program exits with a return value of 0, indicating successful execution.