return the index where maximum element in a vector
To return the index of the maximum element in a vector using C++, you can follow these steps:
- Include the necessary header file:
#include <vector>
- Write a function that takes a vector as input and returns the index of the maximum element:
int findMaxIndex(const std::vector<int>& vec) {
int maxIndex = 0; // Assume the first element is the maximum
for (int i = 1; i < vec.size(); ++i) {
if (vec[i] > vec[maxIndex]) {
maxIndex = i; // Update the maxIndex if a larger element is found
}
}
return maxIndex;
}
- In your main program, create a vector and call the
findMaxIndex
function:
int main() {
std::vector<int> numbers = {5, 2, 9, 7, 3};
int maxIndex = findMaxIndex(numbers);
std::cout << "The maximum element is at index: " << maxIndex << std::endl;
return 0;
}
Explanation:
- Step 1: Including the <vector>
header file allows us to use the vector container in C++.
- Step 2: The findMaxIndex
function takes a constant reference to a vector of integers as its parameter. It initializes maxIndex
to 0, assuming the first element is the maximum. It then iterates through the vector starting from the second element (index 1) and compares each element with the current maximum. If a larger element is found, maxIndex
is updated to the index of that element. Finally, the function returns maxIndex
.
- Step 3: In the main
function, we create a vector called numbers
and initialize it with some values. We then call the findMaxIndex
function, passing numbers
as the argument. The returned index of the maximum element is stored in maxIndex
, which is then printed to the console.
Note: Make sure to include the necessary headers (<vector>
and <iostream>
) and use the std
namespace or qualify the standard library types with std::
prefix as shown in the example.