On Nov 6, 11:35 am, sean_in_rale...@yahoo.com wrote:
> On Nov 6, 9:47 am, Yan <yvinogra...@gmail.com> wrote:
>
>
>
> > I have a vector of elements which I iterate through and call a method
> > on each of the elements. I want to do it using std::for_each
> > algorithm, but having a problem implementing it since the method that
> > I call on each element takes an argument and I don't know how to pass
> > this argument through. Here is the code using an old fashioned loop:
>
> > ......
> > std::vector<unsigned char> bytes;
> > std::vector<T> elements;
> > ...
> > for (int i = 0; i < elements.size(); ++i) {
> > elements[i].serialize(bytes);}
>
> > .........
>
> > could someone please help me out rewrite that using std::for_each?
>
> > Thanks!
>
> Here's the standard-C++ way, though the boost::bind method
> mentioned earlier is more flexible.
>
> class MySerializable
> {
> public:
> void serialize(vector<unsigned char> *b)
> {
> b->push_back(my_bits);
> }
> private:
> unsigned char my_bits;
>
> };
>
> int
Thanks everyone!
Indeed, in this case the good old loop seems easier to write, read,
and, if needed, to debug :)
> main(int argc, char **argv)
> {
> vector<unsigned char> bytes;
> vector<MySerializable> elements;
>
> // ... fill in elements ...
>
> for_each(elements.begin(), elements.end(),
> bind2nd(mem_fun_ref(&MySerializable::serialize),
> &bytes));
>
> }
>
> Sean