You can customize the ordering of the elements in the set by providing a custom predicate to determine ordering of added elements relative to extant members. set is defined as
template < class Key, class Traits=less<Key>, class Allocator=allocator<Key> > class set where Traits is
The type that provides a function object that can compare two element values as sort keys to determine their relative order in the set. This argument is optional, and the binary predicate less is the default value.
There is background on how to use lambda expression as a template parameter herehow to use lambda expression as a template parameter here.
In your case this translates to:
auto comp = [](const string& a, const string& b) -> bool { return a.length() < b.length(); }; auto results = std::set <string, decltype(comp)> (comp); Note that this will result in set elements with the same string length being treated as duplicates which is not what you want, as far as I can understand the desired outcome.