Re: initializing a vector with a sequence of 0, ..., N-1
Rene M?hring wrote:
Carl Barron <cbarron413@adelphia.net> schrieb:
In article <444A7408.20301@iitis.gliwice.pl>, Irek Szczesniak
<ijs@iitis.gliwice.pl> wrote:
For instance, it would be cool to have something like this:
vector<int> index(seq<vector<int> >(0, 9));
Thanks for reading.
there is
template <class T>
class incr
{
T x;
public:
incr(const T &a):x(a){}
T operator () () {return x++;}
};
...
std::vector<int> foo;
std::generate_n(std::back_inserter(foo),10,incr<int> (0));
This looks really complicated in comparison to the for loop.
With the difference that you have to write the full loop each
time you want to do this, whereas you only need to write the
generator once. If you only do it once, it's a net loss; if you
often initialize vectors in this way, it's a gain.
Of course, where it really becomes interesting is when you have
something like this in your toolkit. Or better yet, a toolkit
which someone else has written and maintained. Something like
boost::counting_iterator, which allows writing:
std::vector< int > foo( boost::counting_iterator( 0 ),
boost::counting_iterator( 10 ) ) ;
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]