gather()

So I was watching Bjarne Stroustrups key note from Going Native 2012 and just playing around with some C++. At some point in the video Bjarne discusses a small generic function to move elements satisfying a condition to a certain position in a container.

I took the code, played around with it for a while, and noticed that the code provided would move the elements so that the end of the range of moved elements would be at the position you wanted to move to. This didn’t quite satisfy me, so I rewrote it to place the moved elements starting at said position.

template <typename Iter, typename Predicate>
pair<Iter, Iter> gather(Iter first, Iter last, Iter p, Predicate pred)
{
    // get number of elements to move
    // and move elements to front
    Iter n = stable_partition(first, last, bind(pred, _1));

    // if moving to p would exceed container's
    // bounds move to back of container instead
    if (distance(p, last) < distance(first, n))
        advance(p, distance(p, last) - distance(first, n));

    // need to adjust range to partition
    advance(p, distance(first, n));

    return make_pair(
        // move elements to position
        stable_partition(first, p, bind(not1(pred), _1)),
        p
    );
}