How to get the longest string in a set of strings in c++

Viewed 683

I have a set of strings

set<string> strings;

How do I get the longest string contained in the set? In python I could do the following:

print max(strings, key=len)

Is there a similar function in c++?

1 Answers

You can use std::max_element that ships with the <algorithm> header and pass a custom comparison predicate.

#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";

This is clearly not as concise as the python version, and this is where ranges are to the rescue. With range-v3 projections, this boils down to

#include <range/v3/all.hpp>

const auto longest = ranges::max_element(strings, std::less<>{}, &std::string::size);
Related