Thread: Using std::for_each

  1. #1
    Registered User
    Join Date
    Sep 2001

    Question Using std::for_each

    Quite often (right now actually), I have to do this...
    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?
    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
    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
    In this case, std::copy may be more appropriate, for a container of some type T:
    std::copy(my_container.begin(), my_container.end(),
    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
    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
    Registered User
    Join Date
    May 2006
    Yeah, I would recommend boost.

Popular pages Recent additions subscribe to a feed