Boost logo

Boost Users :

Subject: Re: [Boost-users] Is there a 1 line wonder for counting iterator and back_inserter - say a counting iterator where the start and step can be specified?
From: Krzysztof Czainski (1czajnik_at_[hidden])
Date: 2014-01-05 14:23:51


2014/1/5 Brian Davis <bitminer_at_[hidden]>

>
> Is there a 1 line wonder for counting iterator and back_inserter - say a
> counting iterator where the start and step can be specified?
>
> The following code creates an vector of angles from zero to N-1 * angle
> step;
>
> std::vector angles;
> float angle_step = 0.275;
> int number_angles = 293;
>
> std::copy(
> boost::counting_iterator<float>(0),
> boost::counting_iterator<float>(number_angles),
> std::back_inserter(angles) );
>
> std::copy(
> boost::make_transform_iterator(angles.begin(),
> boost::bind1st(std::multiplies<float>(), angle_step )),
> boost::make_transform_iterator(angles.end(), boost::bind1st(std::multiplies<float>(),
> angle_step )),
> angles.begin() );
>
>
> Is there or could there be a counting iterator or other mechanism to do
> this in 1 line?
> Say where the start and step could be specified?
>
> Thanks
>

I recommend Boost.Range. In your example I also suggest using
Boost.Phoenix instead of bind1st and multiplies; and push_back from
Boost.Range instead of back_inserter.

#include <boost/phoenix/core.hpp>
#include <boost/phoenix/operator.hpp>
#include <boost/range/irange.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/algorithm_ext/push_back.hpp>

#include <iostream>
#include <iterator>
#include <vector>

using namespace boost::phoenix::placeholders;
namespace ad = boost::adaptors;

static int const N = 10;
static float const STEP = 0.5;

int main()
{
    std::vector<float> x, y;

    boost::copy( boost::irange(0,N) | ad::transformed( _1 * STEP ),
std::back_inserter(x) );

    boost::push_back( y, boost::irange(0,N) | ad::transformed( _1 * STEP )
);

    boost::copy( x, std::ostream_iterator<float>(std::cout, " ") );
    std::cout << std::endl;
    boost::copy( y, std::ostream_iterator<float>(std::cout, " ") );
    std::cout << std::endl;
}

Regards,
Kris



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net