Using std::for_each

This is a discussion on Using std::for_each within the C++ Programming forums, part of the General Programming Boards category; Quite often (right now actually), I have to do this... Code: std::container::const_iterator ci; for (ci = my_container.begin(); ci != my_container.end(); ...

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    752

    Question Using std::for_each

    Quite often (right now actually), I have to do this...
    Code:
    std::container::const_iterator ci;
    for (ci = my_container.begin(); ci != my_container.end(); ++ci) {
       std::cout << *ci;
    }
    I would like to use for_each for snippets like this, but can't figure out the syntax. Something like this?
    Code:
    std::for_each( my_container.begin(); my_container.end(); std::cout.operator<<() );
    Callou collei we'll code the way
    Of prime numbers and pings!

  2. #2
    Registered User Noir's Avatar
    Join Date
    Mar 2007
    Posts
    218
    Nice try. No, you have to write a function or a functor that does the output and give it to for_each. The lesson here is that for_each is dumb and you're better off just ignoring it if you don't already have a function that fits the third argument.

  3. #3
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,618
    In this case, std::copy may be more appropriate, for a container of some type T:
    Code:
    std::copy(my_container.begin(), my_container.end(),
              std::ostream_iterator<T>(std::cout));
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,346
    In the next standard there will be tools that make for_each type stuff easier so you don't have to write a functor. Boost already has some stuff for that, although I believe it will be better when it is part of the language.

  5. #5
    l2u
    l2u is offline
    Registered User
    Join Date
    May 2006
    Posts
    630
    Yeah, I would recommend boost.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21