C++获取map最小值算法,STL---std::min_element()!

std::min_element

定义于头文件 

以下是API文档说明!

寻找范围 [first, last) 中的最小元素。

1) 用 operator< 比较元素。
3) 用给定的二元比较函数 comp 比较元素。
2,4) 同 (1,3) ,但按照 policy 执行。这些重载仅若 std::is_execution_policy_v> (C++20 前)std::is_execution_policy_v> (C++20 起) 为 true 才参与重载决议。
参数
first, last    -    定义要检验范围的向前迭代器
policy    -    所用的执行策略。细节见执行策略。
comp    -    比较函数对象(即满足比较 (Compare) 要求的对象),若a 小于 b ,则返回 ​true 。
比较函数的签名应等价于如下:

 bool cmp(const Type1 &a, const Type2 &b);

虽然签名不必有 const & ,函数也不能修改传递给它的对象,而且必须接受(可为 const 的)类型 Type1 与 Type2 的值,无关乎值类别(从而不允许 Type1 & ,亦不允许 Type1 ,除非 Type1 的移动等价于复制 (C++11 起))。
类型 Type1 与 Type2 必须使得 ForwardIt 类型的对象能在解引用后隐式转换到这两个类型。​

类型要求
-ForwardIt 必须满足遗留向前迭代器 (LegacyForwardIterator) 的要求。
返回值
指向范围 [first, last) 中最小元素的迭代器。若范围中有多个元素等价于最小元素,则返回指向首个这种元素的迭代器。若范围为空则返回 last 。

复杂度
准确比较 max(N-1,0) 次,其中 N = std::distance(first, last) 。

异常
拥有名为 ExecutionPolicy 的模板形参的重载按下列方式报告错误:

若作为算法一部分调用的函数的执行抛出异常,且 ExecutionPolicy 为标准策略之一,则调用 std::terminate 。对于任何其他 ExecutionPolicy ,行为是实现定义的。
若算法无法分配内存,则抛出 std::bad_alloc 。

#include 
#include 
#include 

struct MyStruct {
    int value1;
    int value2;
};

bool compareStruct(const MyStruct& struct1, const MyStruct& struct2) {
    // 比较结构体的值
    return struct1.value1 < struct2.value1;
}

int main() {
    std::map myMap;
    myMap[1] = {10, 20};
    myMap[2] = {20, 30};
    myMap[3] = {5, 15};
    myMap[4] = {15, 25};

    // 找到值最小的键值对
    auto minElement = std::min_element(myMap.begin(), myMap.end(),
        [](const auto& lhs, const auto& rhs) {
            return compareStruct(lhs.second, rhs.second);
        });

    if (minElement != myMap.end()) {
        std::cout << "最小的键值对为: (" << minElement->first << ", {" << minElement->second.value1 << ", " << minElement->second.value2 << "})" << std::endl;
    }

    return 0;
}

你可能感兴趣的:(C++学习,算法,c++,开发语言)