correct idiom for container

Discussion in 'C++' started by keith, Apr 8, 2010.

  1. keith

    keith Guest

    Is the following code well-formed and portable?

    Value value;
    Container<Value> c;

    c.push_back(value);
    c.erase(--c.end());

    Container can be std::string, std::vector...
     
    keith, Apr 8, 2010
    #1
    1. Advertising

  2. keith

    Jonathan Lee Guest

    On Apr 8, 11:46 am, Pete Becker <> wrote:
    > It's not quite that simple. If the iterator is a class type you can
    > decrement it. So if the iterator isn't a class type, the code is
    > ill-formed; if the iterator is a class type, the code works fine. But
    > it's not portable.


    Using rbegin() instead of --end() should fix that.

    --Jonathan
     
    Jonathan Lee, Apr 8, 2010
    #2
    1. Advertising

  3. keith

    James Kanze Guest

    On Apr 8, 4:46 pm, Pete Becker <> wrote:
    > Victor Bazarov wrote:
    > > keith wrote:
    > >> Is the following code well-formed and portable?


    > >> Value value;
    > >> Container<Value> c;


    > >> c.push_back(value);
    > >> c.erase(--c.end());


    > >> Container can be std::string, std::vector...


    > > First thing that came to my mind: c.end() returns a
    > > *temporary* which isn't an lvalue. Decrement requires an
    > > lvalue, hence the code that has (--c.end()) is ill-formed.
    > > Ill-formed program cannot be portable. So, the answer to
    > > your question is "No".


    > It's not quite that simple. If the iterator is a class type you can
    > decrement it.


    Maybe. If the iterator is a class type and the increment
    operator is a member, you can decrement it. If the increment
    operator is a free function, taking the iterator as a non-const
    reference, you can't. (I don't know of any implementations
    which do it that way, but I don't know why. It's the way I'd do
    it.)

    --
    James Kanze
     
    James Kanze, Apr 8, 2010
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Vivi Orunitia
    Replies:
    11
    Views:
    4,543
    Martijn Lievaart
    Feb 4, 2004
  2. Maitre Bart
    Replies:
    2
    Views:
    549
    Maitre Bart
    Feb 11, 2004
  3. Steven T. Hatton
    Replies:
    4
    Views:
    3,984
    Rob Williscroft
    Dec 5, 2004
  4. keith

    container idiom revisited

    keith, Apr 13, 2010, in forum: C++
    Replies:
    9
    Views:
    303
    Kai-Uwe Bux
    Apr 15, 2010
  5. Mark Summerfield
    Replies:
    4
    Views:
    62
    Zachary Ware
    Mar 17, 2014
Loading...

Share This Page