我有一组字符串
set<string> strings;
Run Code Online (Sandbox Code Playgroud)
如何获取集合中包含的最长字符串?在python中,我可以执行以下操作:
print max(strings, key=len)
Run Code Online (Sandbox Code Playgroud)
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";
Run Code Online (Sandbox Code Playgroud)
这显然不像python版本那么简洁,这就是范围可以解决的问题.使用range-v3投影,归结为
#include <range/v3/all.hpp>
const auto longest = ranges::max_element(strings, std::less<>{}, &std::string::size);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |