Finding the Position of the Max Element in a Vector in C++
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};
auto maxElement = std::max_element(vec.begin(), vec.end());
int position = std::distance(vec.begin(), maxElement);
std::cout << "The maximum element is " << *maxElement << " at position " << position << std::endl;
return 0;
}
- Include necessary header files.
- Define the main function.
- Create a vector of integers.
- Use
std::max_element
to find the iterator to the maximum element in the vector. - Calculate the position of the maximum element using
std::distance
. - Output the maximum element and its position.