Tech Off Thread

2 posts

a selector iterator

Back to Forum: Tech Off
  • User profile image
    giecrilj71pl

    Stephan T. Lavavej described how to eliminate loops in code using standard algorithms in his excellent installment algorithms and functors.  In particular, he showed how to use an algorithm to count all even numbers in a sequence.

    Is it possible to harness STL to create a list of all even numbers in a sequence, without loops or custom iterators?  I currently use custom iterators for the purpose, but I feel a forward iterator factorization of std::count would be very useful, along the lines of the following code?

    std::count (select (begin, even), end, True) == std::count (begin, end, even)

  • User profile image
    Sven Groot

    You mean something like this?

    std::vector<int> source;
    std::vector<int> dest;
    std::copy_if(source.begin(), source.end(), std::back_inserter(dest), [](int n) { return (n % 2) == 0; });

    EDIT: It seems from your question you want an iterator that selectively skips elements of the underlying sequence. Unfortunately, I don't think you can do that without creating a custom iterator for it, since no such iterator exists in the STL.

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.