Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++11

set

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++?

like image 697
Robbie Cronin Avatar asked Nov 04 '25 02:11

Robbie Cronin


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);
like image 73
lubgr Avatar answered Nov 07 '25 14:11

lubgr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!