在 Java 中,Stream.findFirst()
返回Optional<T>
. 我想对std::ranges::find()
. 如果未找到该值,则返回last
迭代器。如果T
是一个结构,这很不方便,我试图从中取出一个成员。这是一个演示代码:
struct Person {
int age;
int height;
};
std::vector<Person> people;
people.emplace_back(20, 100);
people.emplace_back(23, 170);
// find the height of a 23yo person
std::optional<int> height1 = std::ranges::find(people, 23, &Person::age)->height;
// find the height of a 26yo person
std::optional<int> height2 = std::ranges::find(people, 26, &Person::age)->height; // error
当然,我可以在每个周围放置一些包装器代码find
来转换迭代器,但这会使代码变得如此冗长和样板式。我想知道 C++20 中是否有一些更惯用的方式来做到这一点?
std::optional<int> height2;
auto iter = std::ranges::find(people, 26, &Person::age);
if (iter == people.end()) {
height2 = std::nullopt;
} else {
height2 = iter->height;
}