C++max函数的使用案例20个

文章目录

    • 1. **基本用法:**
    • 2. **比较浮点数:**
    • 3. **比较字符串:**
    • 4. **使用自定义比较函数:**
    • 5. **比较容器中的元素:**
    • 6. **使用`std::initializer_list`:**
    • 7. **变长参数版本(C++11及以上):**
    • 8. **C++17起可用的`std::optional`与`std::max`结合:**
    • 9. **比较结构体成员:**
    • 10. **并行计算环境下的`std::max`(假设使用了并行算法库):**
    • 11. **比较自定义类型的引用计数智能指针**:
    • 12. **使用`std::max`与`std::accumulate`结合计算数组最大值**:
    • 13. **使用`std::max`与`std::transform_reduce`计算两个序列对应元素的最大值**:
    • 14. **比较具有权重的元素**:
    • 15. **动态分配内存时获取最大尺寸**:
    • 16. **在多维数组中查找最大值**:
    • 17. **在关联容器(如map)中查找最大键值对**:
    • 18. **在非连续存储结构中查找最大值**:
    • 19. **使用`std::max`与`std::for_each`结合遍历集合并输出最大值**:
    • 20. **在C++20引入的概念式范围(ranges)中查找最大值**:

以下是一系列C++ std::max函数的使用示例,涵盖不同情境下的应用:

1. 基本用法:

#include <algorithm>

int main() {
    int a = 10, b = 20;
    int max_value = std::max(a, b);
    std::cout << "The maximum value is: " << max_value << std::endl;  // 输出 "20"
    return 0;
}

2. 比较浮点数:

#include <algorithm>

double a = 3.14, b = 2.71;
double max_double = std::max(a, b);
std::cout << "The maximum double is: " << max_double << std::endl;  // 输出 "3.14"

3. 比较字符串:

#include <algorithm>
#include <string>

std::string s1 = "apple", s2 = "banana";
std::string longer_str = std::max(s1, s2);
std::cout << "The longer string is: " << longer_str << std::endl;  // 输出 "banana"

4. 使用自定义比较函数:

struct Person {
    std::string name;
    int age;
};

bool compareAge(const Person& p1, const Person& p2) {
    return p1.age < p2.age;
}

Person p1 = {"Alice", 25}, p2 = {"Bob", 30};
Person older_person = std::max(p1, p2, compareAge);
std::cout << "The older person is: " << older_person.name << std::endl;  // 输出 "Bob"

5. 比较容器中的元素:

#include <algorithm>
#include <vector>

std::vector<int> v = {1, 3, 5, 2, 4};
auto it = std::max_element(v.begin(), v.end());
std::cout << "The maximum element in the vector is: " << *it << std::endl;  // 输出 "5"

6. 使用std::initializer_list

#include <algorithm>
#include <iostream>

int main() {
    int max_num = std::max({10, 20, 30, 5, 15});
    std::cout << "The maximum number from initializer list is: " << max_num << std::endl;  // 输出 "30"
    return 0;
}

7. 变长参数版本(C++11及以上):

#include <algorithm>

template<typename T>
T maxOfMany(const T& first, const T& second, const T& rest...) {
    T result = std::max(first, second);
    va_list args;
    va_start(args, second);
    for (T arg = va_arg(args, T); arg != T(); arg = va_arg(args, T)) {
        result = std::max(result, arg);
    }
    va_end(args);
    return result;
}

int main() {
    int m = maxOfMany(1, 2, 3, 4, 5);
    std::cout << "The maximum of several numbers is: " << m << std::endl;  // 输出 "5"
    return 0;
}

注意:C++标准库并未提供内置的变长参数版本的std::max,上例展示了如何自行实现类似功能。

8. C++17起可用的std::optionalstd::max结合:

#include <optional>
#include <algorithm>

std::optional<int> a = 10, b = 20, c = std::nullopt;
std::optional<int> max_opt = std::max({a, b, c});
if (max_opt.has_value()) {
    std::cout << "The maximum optional value is: " << max_opt.value() << std::endl;  // 输出 "20"
} else {
    std::cout << "No valid optional values provided." << std::endl;
}

9. 比较结构体成员:

#include <algorithm>
#include <tuple>

struct Employee {
    std::string name;
    double salary;
};

auto salary_comparer = [](const Employee& e1, const Employee& e2) {
    return std::tie(e1.salary) < std::tie(e2.salary);
};

Employee e1 = {"Alice", 50000.0}, e2 = {"Bob", 60000.0};
Employee high_salary_employee = std::max(e1, e2, salary_comparer);
std::cout << "Employee with the highest salary is: " << high_salary_employee.name << std::endl;  // 输出 "Bob"

10. 并行计算环境下的std::max(假设使用了并行算法库):

#include <algorithm>
#include <execution>
#include <vector>

std::vector<int> nums = {...};  // 填充大量数据

// 注意:在实际并行环境中,应考虑同步问题和负载均衡
int parallel_max = std::reduce(std::execution::par_unseq, nums.begin(), nums.end(), std::numeric_limits<int>::min(),
                              [](int a, int b) { return std::max(a, b); });

std::cout << "The maximum value computed in parallel is: " << parallel_max << std::endl;

最后一个例子利用了C++17的并行算法库(假设已经存在并行执行策略),但实际上,C++标准库并没有直接提供并行版的std::max,此处使用了std::reduce函数并提供了自定义的组合器来模拟寻找最大值的过程。在真实场景中,使用并行算法库时需要谨慎处理数据同步和其他并发问题。

由于前文已列出10个较全面的std::max使用案例,这里再补充几个较为特殊或进阶的使用方法:

11. 比较自定义类型的引用计数智能指针

```cpp
#include <memory>
#include <algorithm>

struct RefCounted {
    int value;
    std::shared_ptr<int> ref_count;

    bool operator<(const RefCounted& other) const {
        return *ref_count < *other.ref_count;
    }
};

std::vector<std::shared_ptr<RefCounted>> objects = { /*...*/ };
auto max_ref_count_obj = *std::max_element(objects.begin(), objects.end(),
                                           [](const auto& a, const auto& b) {
                                               return *a->ref_count < *b->ref_count;
                                           });

std::cout << "Object with the highest reference count has value: " << max_ref_count_obj->value << std::endl;
```

12. 使用std::maxstd::accumulate结合计算数组最大值

```cpp
#include <numeric>
#include <vector>

std::vector<int> arr = {1, 2, 3, 4, 5};
int max_val = std::accumulate(arr.begin(), arr.end(), std::numeric_limits<int>::min(),
                              [](int acc, int val) { return std::max(acc, val); });

std::cout << "The maximum value in the array is: " << max_val << std::endl;
```

13. 使用std::maxstd::transform_reduce计算两个序列对应元素的最大值

```cpp
#include <numeric>
#include <vector>

std::vector<int> a = {1, 2, 3};
std::vector<int> b = {4, 5, 6};

// 确保两个向量长度一致
assert(a.size() == b.size());

int max_pairwise = std::transform_reduce(
    a.begin(), a.end(), b.begin(), std::numeric_limits<int>::min(),
    [](int a, int b) { return std::max(a, b); },
    [](int acc, int val) { return std::max(acc, val); }
);

std::cout << "The maximum pairwise value is: " << max_pairwise << std::endl;
```

14. 比较具有权重的元素

```cpp
struct WeightedValue {
    int value;
    int weight;
};

bool compareWeighted(const WeightedValue& w1, const WeightedValue& w2) {
    return w1.weight * w1.value < w2.weight * w2.value;
}

std::vector<WeightedValue> weightedValues = { /*...*/ };
auto max_weighted = *std::max_element(weightedValues.begin(), weightedValues.end(), compareWeighted);

std::cout << "The most valuable item considering weight is: " << max_weighted.value << std::endl;
```

15. 动态分配内存时获取最大尺寸

```cpp
#include <vector>
#include <algorithm>

std::vector<std::unique_ptr<int[]>> arrays = { /*...*/ };
int max_size = std::max_element(arrays.begin(), arrays.end(),
                                [](const auto& a, const auto& b) {
                                    return a->size() < b->size();
                                })->size();

std::cout << "The maximum allocated size among the arrays is: " << max_size << std::endl;
```

以上案例展示了在更复杂的数据结构和场景中如何巧妙地运用std::max函数,同时也体现了C++泛型编程的优势。

16. 在多维数组中查找最大值

```cpp
#include <algorithm>
#include <array>

std::array<std::array<int, 3>, 2> matrix = {{{1, 2, 3}, {4, 5, 6}}};
int max_in_matrix = *std::max_element(matrix.begin(), matrix.end(),
                                     [](const auto& row1, const auto& row2) {
                                         return *std::max_element(row1.begin(), row1.end()) <
                                                *std::max_element(row2.begin(), row2.end());
                                     });

std::cout << "The maximum value in the matrix is: " << max_in_matrix << std::endl;  // 输出 "6"
```

17. 在关联容器(如map)中查找最大键值对

```cpp
#include <algorithm>
#include <map>

std::map<std::string, int> scores = {{"Alice", 90}, {"Bob", 95}, {"Charlie", 92}};
auto max_entry = *std::max_element(scores.begin(), scores.end(),
                                   [](const auto& pair1, const auto& pair2) {
                                       return pair1.second < pair2.second;
                                   });

std::cout << "The student with the highest score is: " << max_entry.first << ", with a score of " << max_entry.second << std::endl;
```

18. 在非连续存储结构中查找最大值

```cpp
#include <algorithm>
#include <deque>

std::deque<int> deque_with_gaps = {1, 2, 4, 8, 16, 32, 64};
auto max_deque = *std::max_element(deque_with_gaps.begin(), deque_with_gaps.end());

std::cout << "The maximum value in the deque is: " << max_deque << std::endl;  // 输出 "64"
```

19. 使用std::maxstd::for_each结合遍历集合并输出最大值

```cpp
#include <algorithm>
#include <set>
#include <iostream>

std::set<int> unique_numbers = {1, 2, 3, 4, 5};
int current_max = std::numeric_limits<int>::min();
std::for_each(unique_numbers.begin(), unique_numbers.end(),
              [&](const int& num) {
                  current_max = std::max(current_max, num);
              });

std::cout << "The maximum value in the set is: " << current_max << std::endl;  // 输出 "5"
```

20. 在C++20引入的概念式范围(ranges)中查找最大值

```cpp
#include <ranges>

std::vector<int> vec = {1, 2, 3, 4, 5};
int max_range = std::ranges::max(vec);

std::cout << "The maximum value in the range-based view is: " << max_range << std::endl;  // 输出 "5"
```

这些案例展示了std::max在不同数据结构和容器中的应用,包括多维数组、关联容器、非连续存储结构以及C++20的新特性——概念式范围。
python推荐学习汇总连接:
50个开发必备的Python经典脚本(1-10)

50个开发必备的Python经典脚本(11-20)

50个开发必备的Python经典脚本(21-30)

50个开发必备的Python经典脚本(31-40)

50个开发必备的Python经典脚本(41-50)
————————————————

​最后我们放松一下眼睛
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/430095.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

c++的队列的用法

基本介绍 c的队列就是std::queue。 需要包含的头文件&#xff1a; #include<queue>queue就是先进先出队列 queue,就是队列&#xff0c;队列是一种容器适配器&#xff0c;专门设计用于在FIFO上下文中操作(先进先出)&#xff0c;其中将元素插入容器的一端并从另一端提…

广东Lenovo SR588服务器维修升级硬盘内存

本案例描述了对联想SR588服务器进行硬件升级的过程&#xff0c;包括更换固态硬盘作为系统盘&#xff0c;以及增加内存容量至128GB。升级后&#xff0c;服务器性能得到显著提升&#xff0c;同时通过重新配置RAID阵列和操作系统的重新安装&#xff0c;确保了系统的稳定性和数据的…

华为路由器 三层交换实现vlan通信 实验(附ensp实验源文件)

一、目标 通过三层交换实现vlan通信 二、网络配置 2.1 交换机1&#xff08;LSW1&#xff09;配置 # 创建两个vlan vlan 10 vlan 20# 配置g0/0/1端口 port link-type access port default vlan 10# 配置g0/0/2端口 port link-type access port default vlan 20# 配置g0/0/3端口…

STM32F1 - SPI读写Flash

Serial peripheral interface 1> 实验概述2> SPI硬件框图初始化程序 3> STM32的SPI通信时序3.1> 时序图3.2> 文字描述3.3> 注意事项3.4> 流程图表示3.5> 程序表示接收程序&#xff1a;发送程序&#xff1a; 4> SPI的4种模式5> W25Q128存储结构块…

开发知识点-Python-爬虫

爬虫 scrapybeautifulsoupfind_all find祖先/父节点兄弟节点nextpreviousCSS选择器属性值 attrsselect 后 class 正则使用字符串来描述、匹配一系列符合某个规则的字符串组成元字符使用grep匹配正则组与捕获断言与标记条件匹配正则表达式的标志 特定中文 匹配 scrapy scrapy内…

ssm+springboot音乐播放器网站mybatis+jsp

测试流程 &#xff08;1&#xff09; 登录系统、填写用户名、密码选择角色&#xff0c;主要内容&#xff1a;进行权限控制。 &#xff08;2&#xff09; 用户查看音乐信息、音乐资讯功能&#xff0c;主要是测试系统实用性、方便性。 &#xff08;3&#xff09; 信息修…

B084-SpringCloud-Zuul Config

目录 zuul系统架构和zuul的作用zuul网关实现配置映射路径过滤器 Config概述云端管理本地配置 zuul zuul是分布式和集群后前端统一访问入口 系统架构和zuul的作用 zuul把自己注册进eureka&#xff0c;然后可通过前端传来的服务名发现和访问对应的服务集群 为了预防zuul单点故…

在Java中处理JSON数据:Jackson与Gson库比较

引言 JSON&#xff0c;作为一种轻量级的数据交换格式&#xff0c;因其易于人阅读和编写&#xff0c;同时也易于机器解析和生成&#xff0c;而被广泛应用于网络通信和配置文件中。在Java中&#xff0c;有两个强大的工具帮助咱们处理JSON数据——Jackson和Gson。这两个库各有千秋…

Conda 快速入门,轻松拿捏 Python

一、简介 Conda 是一个开源的软件包管理系统和环境管理系统&#xff0c;用于安装多个版本的软件包及其依赖关系&#xff0c;并在它们之间轻松切换。Conda 是为 Python 程序创建的&#xff0c;适用于 Linux&#xff0c;OS X 和Windows&#xff0c;也可以打包和分发其他软件&…

teknoparrot命令行启动游戏

官方github cd 到teknoparrot解压目录 cd /d E:\mn\TeknoParrot2_cp1\GameProfiles启动游戏 TeknoParrotUi.exe --profile游戏配置文件游戏配置文件位置/UserProfiles,如果UserProfiles文件夹里没有那就在/GameProfiles,在配置文件里将游戏路径加入之间,或者打开模拟器设置 …

SpringCloud Alibaba 学习

一&#xff1a;SpringCloud Alibaba介绍 Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案。此项目包含开发分布式应用微服 务的必需组件&#xff0c;方便开发者通过 Spring Cloud 编程模型轻松使用这些组件来开发分布式应用服务。 依托 Spring Cloud Alibaba&…

mybatis不重复列插入例子详细说明

之前有做过不重复列插入的需求&#xff0c;当时是 在插入时判断 对应的列在数据库中有没有对应的数据 有则返回false 无则插入&#xff0c;但是这加大了数据库的查询负担 也增加了插入的时间&#xff0c;故今天研究一下 使用sql来简化了这一点 使用的知识点是 daul表 insert i…

提升效率的电脑定时工具,AutoOff软件推荐

今天最软库给大家带来一款非常实用的电脑定时关机软件在我们日常办公的时候有的时候需要上传一些资料由于我们下班了&#xff0c;我们想让他上传完成之后我们才离开这时候呢&#xff0c;就可以用到这款定时工具了。 我们可以设置中设置在几小时或者几分钟之后让电脑进行关机我们…

JDK、JRE、JVM的联系区别

在第一章中我们介绍了JDK的下载配置与IDEA开发环境的下载安装&#xff0c;以及分别在这两个&#xff08;电脑本机和IDEA&#xff09;环境上执行了我们的第一个源程序。通过直观的使用&#xff0c;我们可以感受到集成开发环境的便捷。 大家也更加对JDK有了直观的了解&#xff0c…

【千字总结】爬虫学习指南-2024最新版

介绍 如何自学爬虫&#xff1f;今天有一个兄弟这样问我&#xff0c;可以看到打了很多字&#xff0c;诚意肯定是很足的&#xff0c;也是对我的内容给予了肯定&#xff0c;让我非常的开心。既然难得有人问我&#xff0c;那我一定要好好做一个回答。 我下面将要说的内容没有任何话…

制作耳机壳的UV树脂和塑料材质相比优势有哪些?

制作耳机壳的UV树脂相比塑料材质有以下优势&#xff1a; 高强度与耐磨性&#xff1a;UV树脂具有高强度和耐磨性&#xff0c;能够更好地保护耳机内部零件&#xff0c;延长耳机使用寿命。相比之下&#xff0c;塑料材质可能较易磨损或刮伤。耐高温&#xff1a;UV树脂具有较好的耐…

探索Java开发面试笔记:以听为目的,助力编程技术提升与面试准备

文章目录 一、制作背景介绍二、 Java开发面试笔记&#xff1a;为你的编程之路加速2.1 公众号主题和目标读者群体2.2 为什么面试笔记对于提高编程视野和技术至关重要2.3 親測效率 三、形式案例3.1 文章形式3.2 手机案例3.3 电脑案例 一、制作背景介绍 做公众号的背景&#xff1a…

瑞_23种设计模式_享元模式

文章目录 1 享元模式&#xff08;Flyweight Pattern&#xff09;1.1 介绍1.2 概述1.3 享元模式的结构1.4 享元模式的优缺点1.5 享元模式的使用场景 2 案例一2.1 需求2.2 代码实现 3 案例二3.1 需求3.2 代码实现 4 JDK源码解析&#xff08;Integer类&#xff09; &#x1f64a; …

公园常见污水处理需要哪些设备

根据我了解的情况&#xff0c;公园常见的污水处理需要以下几种设备&#xff1a; 1、格栅机&#xff1a;格栅机是污水处理的第一道工序&#xff0c;用于过滤掉污水中的大颗粒杂物和固体废物&#xff0c;防止其进入后续处理装置。 2、沉淀池&#xff1a;沉淀池用于将污水中的悬浮…

Platformview在iOS与Android上的实现方式对比

Android中早期版本Platformview的实现基于Virtual Display。VirtualDisplay方案的原理是&#xff0c;先将Native View绘制到虚显&#xff0c;然后Flutter通过从虚显输出中获取纹理并将其与自己内部的widget树进行合成&#xff0c;最后作为Flutter在 Android 上更大的纹理输出的…
最新文章