【STL】C++max_element()函数用法

在 C++ 中,std::max_element 是一个标准库算法,定义在 <algorithm> 头文件中,用于在指定范围内查找最大元素的迭代器。

时间复杂度:\(O(n)\),其中\(n\)是范围 \([first, last)\) 中的元素个数。因为需要遍历整个范围来找到最大元素。

取数组中元素最大值的下标

vector<int> a;
int maxvalue_index = max_element(a.begin(), a.end()) - a.begin();
int b[N]; // 设长度为n
int maxvalue_index = max_element(b, b + n) - b;

取数组某段区间内元素最大值的下标

取数组nums在区间[l, r)(左闭右开)最大值下标

vector<int> nums;
int maxvalue_index = max_element(nums.begin() + l, nums.begin() + r) - nums.begin();

取数组中的元素最大值,在函数前面加*即可取元素的值

vector<int> a;
int max_value = *max_element(a.begin(), a.end());
int b[N]; // 设长度为n
int max_value = *max_element(b, b + n);

自定义比较函数

#include <iostream>
#include <algorithm>
#include <vector>

// 自定义比较函数,比较元素的绝对值
bool abs_compare(int a, int b) {
    return std::abs(a) < std::abs(b);
}

int main() {
    std::vector<int> numbers = {-3, 1, -4, 1, -5, 9, 2, 6, -5, 3, 5};

    // 使用自定义比较函数查找绝对值最大的元素的迭代器
    auto max_it = std::max_element(numbers.begin(), numbers.end(), abs_compare);

    if (max_it != numbers.end()) {
        std::cout << "绝对值最大的元素是: " << *max_it << std::endl;
        std::cout << "绝对值最大的元素的索引是: " << std::distance(numbers.begin(), max_it) << std::endl;
    }

    return 0;
}
posted @ 2025-02-15 18:31  Tshaxz  阅读(1453)  评论(0)    收藏  举报
Language: HTML