std::for_each + break

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • yurec

    #1

    std::for_each + break

    Hi

    I wanna give template method of library class with some predicate,
    which I put to std::for_each in that method.How to break the
    std::for_each with predicate?(exce ptions are used olny in exceptional
    situations, as i know)

    Thanks
  • alan

    #2
    Re: std::for_each + break

    On Nov 19, 8:12 pm, yurec <Yurij.Zha...@m aterialise.kiev .uawrote:
    Hi
    >
    I wanna give template method of library class with some predicate,
    which I put to std::for_each in that method.How to break the
    std::for_each with predicate?(exce ptions are used olny in exceptional
    situations, as i know)
    >
    Thanks
    Perhaps you would be better served by std::find_if

    Comment

    • yurec

      #3
      Re: std::for_each + break

      On Nov 19, 2:17 pm, alan <almkg...@gmail .comwrote:
      On Nov 19, 8:12 pm, yurec <Yurij.Zha...@m aterialise.kiev .uawrote:
      >
      Hi
      >
      I wanna give template method of library class with some predicate,
      which I put to std::for_each in that method.How to break the
      std::for_each with predicate?(exce ptions are used olny in exceptional
      situations, as i know)
      >
      Thanks
      >
      Perhaps you would be better served by std::find_if
      For sure, thx

      Comment

      • James Kanze

        #4
        Re: std::for_each + break

        On Nov 19, 1:12 pm, yurec <Yurij.Zha...@m aterialise.kiev .uawrote:
        I wanna give template method of library class with some
        predicate, which I put to std::for_each in that method.How to
        break the std::for_each with predicate?(exce ptions are used
        olny in exceptional situations, as i know)
        You can't. That's precisely the point of for_each.

        --
        James Kanze (GABI Software) email:james.kan ze@gmail.com
        Conseils en informatique orientée objet/
        Beratung in objektorientier ter Datenverarbeitu ng
        9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

        Comment

        • Kira Yamato

          #5
          Re: std::for_each + break

          On 2007-11-19 07:12:29 -0500, yurec <Yurij.Zhacun@m aterialise.kiev .uasaid:
          Hi
          >
          I wanna give template method of library class with some predicate,
          which I put to std::for_each in that method.How to break the
          std::for_each with predicate?(exce ptions are used olny in exceptional
          situations, as i know)
          >
          Thanks
          I would think throwing an exception is a simple and elegant solution here.

          Just because we have called a mechanism 'exception' and gave it the
          connotation that it is for error-handling purposes, does not mean that
          we can only use the mechanism as such and nothing else.

          Ok, so some runtime cost is needed to setup try-catch blocks, but I'm
          not sure scanning the list twice with find_if/for_each combo is
          necessarily faster.

          --

          -kira

          Comment

          • yurec

            #6
            Re: std::for_each + break

            /* doesn't compile :(
            maybe somebody knows where is my mistake?

            using namespace boost::lambda;
            get_layout_func _map::const_ite rator iter_func =
            std::find_if(na med_func_map.be gin(), named_func_map. end(),

            bind(&IContextT oLayoutPred::Co mpare, ip_pred,

            bind(&get_layou t_func_map::val ue_type::second , _1)));
            */

            //compiles ok!
            get_layout_func _map::const_ite rator iter_func =
            named_func_map. begin();
            const get_layout_func _map::const_ite rator iter_func_end =
            named_func_map. end();
            while (iter_func_end != iter_func)
            {
            if (true == ip_pred->Compare(iter_f unc->second))
            break;

            ++iter_func;
            }

            Comment

            • Sohail Somani

              #7
              Re: std::for_each + break

              On Tue, 20 Nov 2007 11:04:40 -0800, James Kanze wrote:
              Anyone who wrote that at any place where I've ever worked would not be
              allowed to touch the code again. Exceptions are NOT a flow control
              mechanism.
              You should look at the Boost Graph Library's visitor mechanism then. From
              what I recall, it used exceptions to stop visiting something or the other.

              :-)

              --
              Sohail Somani
              Blogger is a blog publishing tool from Google for easily sharing your thoughts with the world. Blogger makes it simple to post text, photos and video onto your personal or team blog.

              Comment

              • Kira Yamato

                #8
                Re: std::for_each + break

                On 2007-11-20 14:04:40 -0500, James Kanze <james.kanze@gm ail.comsaid:
                On Nov 20, 1:13 pm, Kai-Uwe Bux <jkherci...@gmx .netwrote:
                >terminator wrote:
                >>On Nov 20, 12:45 pm, Kai-Uwe Bux <jkherci...@gmx .netwrote:
                >
                >>>try {
                >>>std::for_eac h( seq.begin(), seq.end(), throwing_predic ate_and_actio
                n
                >>>);
                >>>}
                >>>catch ( whatever ) {}
                >
                Anyone who wrote that at any place where I've ever worked would
                not be allowed to touch the code again. Exceptions are NOT a
                flow control mechanism.
                Any boss who think like that I would not want to work for.

                Exception is certainly a flow control mechanism. Essentially it is a
                glorified longjmp with smart stack unwinding that invokes destructors.
                If it looks like a duck and quakes like a duck, then it is a duck.

                Now of course, the question remains when is the proper use of such type
                of flow control. Is it *always* only valid for error handling purposes
                and nothing else? That I cannot say I have enough experience to
                answer, but I find it hard to believe that there is no other uses of an
                inter-stackframe branching mechanism that is aware of cleaning up
                objects in those frames, beside error handling.

                But I like to bring up one possible use:

                In some of the algorithm books I've been reading, many of them have
                terminating statements (like 'return') nested deeply in nested loops.
                So, once a certain terminating condition is reached, the entire
                algorithm is done and exited. If the entire algorithm has been
                implemented in a single function, then the 'return' statement is
                sufficient to exit the algorithm. But what if helper functions were
                used and that the terminating conditions are inside these helper
                functions? In this case, you can either have the helper functions
                return a terminating return code or you can have the main function
                setup a try-catch block and let the helper function throw an exception.
                Now imagine what if helper functions can have helper functions too.
                Don't you think throwing an exception here is the easiest way to return
                control to the main function?

                Of course, some people believe that 'return' statements should never be
                in the middle of a function. A good implementation of an algorithm
                would have every control flow reach the last statement before the
                function-ending braces. If this is your philosophy, then to you
                exception-handling should be used for error-purposes only.
                >
                [...]
                --

                -kira

                Comment

                • Kira Yamato

                  #9
                  Re: std::for_each + break

                  On 2007-11-20 04:45:36 -0500, Kai-Uwe Bux <jkherciueh@gmx .netsaid:
                  Kira Yamato wrote:
                  >
                  >On 2007-11-19 07:12:29 -0500, yurec <Yurij.Zhacun@m aterialise.kiev .ua>
                  >said:
                  >>
                  >>Hi
                  >>>
                  >>I wanna give template method of library class with some predicate,
                  >>which I put to std::for_each in that method.How to break the
                  >>std::for_ea ch with predicate?(exce ptions are used olny in exceptional
                  >>situations, as i know)
                  >>>
                  >>Thanks
                  >>
                  >I would think throwing an exception is a simple and elegant solution here.
                  >
                  Simple and elegant? in this case?
                  >
                  Compare
                  >
                  try {
                  std::for_each( seq.begin(), seq.end(), throwing_predic ate_and_action );
                  }
                  catch ( whatever ) {}
                  >
                  to
                  >
                  for ( iterator_type iter = seq.begin();
                  iter != seq.end() && ! break_condition ( *iter );
                  ++iter ) {
                  some_action( *iter );
                  }
                  >
                  I cannot say that I find the try-throw-catch version easier to grok or more
                  elegant.
                  Hmm. The for-loop code looks more explicit than the for_each. So, why
                  do we bother with for_each again?

                  Or I should ask, why would we ever prefer a statement over a block?
                  >
                  [...]
                  >
                  --

                  -kira

                  Comment

                  • Sohail Somani

                    #10
                    Re: std::for_each + break

                    On Tue, 20 Nov 2007 15:51:12 -0500, Kira Yamato wrote:
                    Hmm. The for-loop code looks more explicit than the for_each. So, why
                    do we bother with for_each again?
                    >
                    Or I should ask, why would we ever prefer a statement over a block?
                    Because it is easier to understand statements than instructions. Compare:

                    namespace bl=boost::lambd a; http://www.boost.org/doc/html/lambda.html
                    ....
                    std::transform( vec1.begin(),ve c1.end(),vec2.b egin(),bl::_1 + 1);

                    To:

                    for(int i = 0; i < vec1.size(); ++i)
                    {
                    vec2[i] = vec2[i] + 1;
                    }

                    Over time, given enough use of the C++ standard library, you can gain an
                    understanding of what code is doing by casual reading without having to
                    scrutinize what the code is doing at the instruction level. So in the
                    first example, it is obvious from reading a single line of code, that
                    someone is intending to add 1 to each element in a vector and assign it
                    to another. I need to read and grok 5 lines for the second version.

                    At least that is my 2 minute explanation!

                    --
                    Sohail Somani
                    Blogger is a blog publishing tool from Google for easily sharing your thoughts with the world. Blogger makes it simple to post text, photos and video onto your personal or team blog.

                    Comment

                    • alan

                      #11
                      Re: std::for_each + break

                      On Nov 20, 11:31 pm, yurec <Yurij.Zha...@m aterialise.kiev .uawrote:
                      /* doesn't compile :(
                      maybe somebody knows where is my mistake?
                      >
                      using namespace boost::lambda;
                      get_layout_func _map::const_ite rator iter_func =
                      std::find_if(na med_func_map.be gin(), named_func_map. end(),
                      >
                      bind(&IContextT oLayoutPred::Co mpare, ip_pred,
                      >
                      bind(&get_layou t_func_map::val ue_type::second , _1)));
                      */
                      Try creating a simple member function that returns the member data
                      'second' of a get_layout_func _map:
                      <your return type hereget_layout_ func_map::get_s econd(){
                      return second;
                      }

                      then replace get_layout_func _map::value_typ e::second with
                      get_layout_func _map::get_secon d. As an aside, you might also
                      profitably add "inline" to the above member function, if you take care
                      to add the definition to the header file.

                      get_layout_func _map::value_typ e may not exist in your
                      get_layout_func _map class, and even if it does, it might not have a
                      member called second. Did you (or who created get_layout_func _map, or
                      one of its public base types) write such a member?

                      boost::bind requires the first argument to be either function or a
                      function object (i.e. belonging to a class that overloads the ()
                      operator or function call operator)
                      >
                      //compiles ok!
                      get_layout_func _map::const_ite rator iter_func =
                      named_func_map. begin();
                      const get_layout_func _map::const_ite rator iter_func_end =
                      named_func_map. end();
                      while (iter_func_end != iter_func)
                      {
                      if (true == ip_pred->Compare(iter_f unc->second))
                      break;
                      >
                      ++iter_func;
                      }
                      This seems quite clear enough; using boost::bind may just make things
                      look more horrible.

                      Comment

                      • alan

                        #12
                        Re: std::for_each + break

                        On Nov 21, 4:51 am, Kira Yamato <kira...@earthl ink.netwrote:
                        On 2007-11-20 04:45:36 -0500, Kai-Uwe Bux <jkherci...@gmx .netsaid:
                        >
                        >
                        >
                        Kira Yamato wrote:
                        >
                        On 2007-11-19 07:12:29 -0500, yurec <Yurij.Zha...@m aterialise.kiev .ua>
                        said:
                        >
                        >Hi
                        >
                        >I wanna give template method of library class with some predicate,
                        >which I put to std::for_each in that method.How to break the
                        >std::for_eac h with predicate?(exce ptions are used olny in exceptional
                        >situations, as i know)
                        >
                        >Thanks
                        >
                        I would think throwing an exception is a simple and elegant solution here.
                        >
                        Simple and elegant? in this case?
                        >
                        Compare
                        >
                        try {
                        std::for_each( seq.begin(), seq.end(), throwing_predic ate_and_action );
                        }
                        catch ( whatever ) {}
                        >
                        to
                        >
                        for ( iterator_type iter = seq.begin();
                        iter != seq.end() && ! break_condition ( *iter );
                        ++iter ) {
                        some_action( *iter );
                        }
                        >
                        I cannot say that I find the try-throw-catch version easier to grok or more
                        elegant.
                        >
                        Hmm. The for-loop code looks more explicit than the for_each. So, why
                        do we bother with for_each again?
                        So we won't have to bother with iterators, which are just pointers in
                        pretty clothes?
                        >
                        Or I should ask, why would we ever prefer a statement over a block?
                        >
                        >
                        >
                        [...]
                        >
                        --
                        >
                        -kira

                        Comment

                        • Sohail Somani

                          #13
                          Re: std::for_each + break

                          On Tue, 20 Nov 2007 22:26:10 +0100, Alf P. Steinbach wrote:
                          >std::transform (vec1.begin(),v ec1.end(),vec2. begin(),bl::_1 + 1);
                          >>
                          >To:
                          >>
                          >for(int i = 0; i < vec1.size(); ++i)
                          >{
                          > vec2[i] = vec2[i] + 1;
                          >}
                          >>
                          >
                          The second code snippet is by far most clear and at-a-glance.
                          >
                          However, it caused me to look twice because it's so non-idiomatic,
                          Pascal style that at first glance one thinks there must be some reason
                          for that, that it doesn't do what it seems to: in C++ we use ++.
                          Sure! You also managed to miss the deliberate bug which was part of the
                          point :-)

                          --
                          Sohail Somani
                          Blogger is a blog publishing tool from Google for easily sharing your thoughts with the world. Blogger makes it simple to post text, photos and video onto your personal or team blog.

                          Comment

                          • Sohail Somani

                            #14
                            Re: std::for_each + break

                            On Tue, 20 Nov 2007 23:55:43 +0100, Alf P. Steinbach wrote:
                            * Sohail Somani:
                            >On Tue, 20 Nov 2007 23:03:46 +0100, Alf P. Steinbach wrote:
                            >>
                            Then I guess that in your view the first snippet defined the wished for
                            effect, and the second had a "bug" in the sense that it didn't do the
                            same?
                            >
                            If so, then you're suffering from the "others should read my mind"
                            syndrome.
                            Dude chill. If you read the rest of the email, I did concede that! In
                            fact, its the next line you quote:
                            >but I suppose the example wasn't full enough. I'll let you off this
                            >time.
                            [snip]
                            Grumble,
                            And how!

                            --
                            Sohail Somani
                            Blogger is a blog publishing tool from Google for easily sharing your thoughts with the world. Blogger makes it simple to post text, photos and video onto your personal or team blog.

                            Comment

                            • Sohail Somani

                              #15
                              Re: std::for_each + break

                              On Tue, 20 Nov 2007 17:18:24 -0800, Kai-Uwe Bux wrote:
                              However, it does not actually present any data in support of the claim
                              that generic algorithms tend to introduce the kind of bug you pointed
                              out.
                              I'm done with this thread, but I just want to point out that there was no
                              bug. That is an intended mode of use for std::transform: Perform an
                              operation on each element in an array and assign it to another.

                              --
                              Sohail Somani
                              Blogger is a blog publishing tool from Google for easily sharing your thoughts with the world. Blogger makes it simple to post text, photos and video onto your personal or team blog.

                              Comment

                              Working...