In C#, I can create an iterator (or IEnumerable
in C# land) which takes another iterator and selects a member of the original type:
class ParentType
{
public MemberType member { get; private set; }
}
// And somewhere else
IEnumerable<Memb开发者_开发问答erType> getMembers(IEnumerable<ParentType> parents)
{
for each (ParentType parent in parents)
yield return parent.member;
}
How would I do a similar operation in C++, where I want to basically take an iterator of a type, and return an iterator which iterates over a particular member?
Hm, with LINQ it's even easier:
var m = from p in parents
select p.member;
or
var m = parents.Select(_ => _.member);
Unfortunately, you can't write lazy enumerations that easy out of the box in c++... Without resorting to an external library you can write an 'eager' selector (a pain w/o local lambdas though):
std::transform(
parents.begin(), parents.end(),
std::back_inserter(members), [] (const parent& p) -> member {
return p.member;
});
精彩评论