开发者

Converting a C++ Iterator into an Iterator over a Member (Select iterator?)

开发者 https://www.devze.com 2023-01-10 10:57 出处:网络
In C#, I can create an iterator (or IEnumerable in C# land) which takes another iterator and selects a member of the original type:

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;
 });
0

精彩评论

暂无评论...
验证码 换一张
取 消