使用 <algorithm>
头文件来查找数组或向量中最大值、最小值及其索引
#include <iostream>
#include <vector>
#include <algorithm> // 包含 std::max_element 和 std::min_element
int main() {
std::vector<int> vec = {3, 1, 4, 2, 5};
// 查找最大值及其索引
auto maxIt = std::max_element(vec.begin(), vec.end());
int maxValue = *maxIt;
int maxIndex = std::distance(vec.begin(), maxIt);
// 查找最小值及其索引
auto minIt = std::min_element(vec.begin(), vec.end());
int minValue = *minIt;
int minIndex = std::distance(vec.begin(), minIt);
// 输出向量内容
std::cout << "向量: ";
for (int num : vec) {
std::cout << num << " ";
}
std::cout << "\n";
// 输出最大值及其索引
std::cout << "最大值: " << maxValue << ",索引: " << maxIndex << "\n";
// 输出最小值及其索引
std::cout << "最小值: " << minValue << ",索引: " << minIndex << "\n";
return 0;
}
解释
std::max_element
和 std::min_element
函数:
std::max_element(vec.begin(), vec.end())
返回指向向量中最大元素的迭代器。
std::min_element(vec.begin(), vec.end())
返回指向向量中最小元素的迭代器。
std::distance(vec.begin(), maxIt)
和 std::distance(vec.begin(), minIt)
分别计算最大元素和最小元素的索引。
注意事项:
确保在使用 std::max_element
和 std::min_element
之前检查向量不为空,以避免未定义的行为。