c++11 - 如何在c ++中获取一组字符串中最长的字符串
问题描述
我有一组字符串
set<string> strings;
如何获得集合中包含的最长字符串?在 python 中,我可以执行以下操作:
print max(strings, key=len)
c++中是否有类似的功能?
解决方案
您可以使用标题std::max_element
附带的<algorithm>
内容并传递自定义比较谓词。
#include <algorithm>
#include <iostream>
const auto longest = std::max_element(strings.cbegin(), strings.cend(),
[](const std::string& lhs, const std::string& rhs) { return lhs.size() < rhs.size(); });
if (longest != strings.cend())
std::cout << *longest << "\n";
这显然不如 python 版本简洁,而这正是 range 的用武之地。使用range-v3投影,这归结为
#include <range/v3/all.hpp>
const auto longest = ranges::max_element(strings, std::less<>{}, &std::string::size);
推荐阅读
- sql - SQL Server 2014 - 选择具有两个条件的语句
- reactjs - React 和 Material UI - 如何向后查找布局、大小和容器信息
- php - 复制网站后的 Wordpress 主页不起作用
- angular - 承诺解决在需要值时返回未定义
- php - Laravel & Stripe - 无法识别的请求 URL (GET: /v1/customers/)
- reactjs - 从循环中更新 react-redux 存储
- javascript - 无法将 ref id 发布到父集合 mongoDB
- asp.net-core - Kofax KTA TotalAgility SDK ASP.NET Core
- postgresql - 将策略附加到具有 RDS 权限的 IAM 用户后,用户权限的 PAM 身份验证失败
- postgresql - Docker 连接到具有特定主机地址的 postgres