ranges/tosortedperson.cpp
The following code example is taken from the book
C++23 - The Complete Guide
by Nicolai M. Josuttis,
Leanpub, 2026
The code is licensed under a
Creative Commons Attribution 4.0 International License.
//
raw code
#include
<print>
#include
<string>
#include
<vector>
#include
<set>
#include
<ranges>
#include
<algorithm>
class
Person
{
private
:
std::string _name;
public
:
Person(
const
std::string& s = {}) : _name{s} {}
Person(
const
char
* s) : _name{s} {}
bool
operator
<(
const
Person& p)
const
{
std::println(
"- compare {} with {}"
, _name, p._name);
return
_name < p._name;
}
auto
name()
const
{
return
_name;}
auto
size()
const
{
return
_name.size();}
};
int
main()
{
std::vector<Person> coll{
"Rome"
,
"Berlin"
,
"Kiev"
,
"LA"
,
"Tokyo"
,
"Cairo"
};
std::println(
"*** init view:"
);
auto
v = coll
| std::views::filter([] (
auto
p) {
return
p.size() > 2; })
// significant size
| std::ranges::to<std::multiset>()
// sorted
| std::views::drop(1)
// skip first
;
std::println(
"*** use view:"
);
for
(
const
auto
& p : v) {
std::print(
"{} "
, p.name());
};
std::print(
"\n"
);
}