首页 > 解决方案 > 如何在c ++中获取一组字符串中最长的字符串

问题描述

我有一组字符串

set<string> strings;

如何获得集合中包含的最长字符串?在 python 中,我可以执行以下操作:

print max(strings, key=len)

c++中是否有类似的功能?

标签: c++11set

解决方案


您可以使用标题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);

推荐阅读