Re: std::vector iterator arithmetic

Discussion in 'C++' started by Bo Persson, Oct 11, 2009.

  1. Bo Persson

    Bo Persson Guest

    Michael D. Berger wrote:
    > Is std::vector arithmetic allowed? For example:
    >
    > std::vector<unsigned> vec;
    >
    > ... // put things in vec .
    >
    > vec.erase(vec.begin(),vec.begin()+2);
    >
    > erases first two item in vec . OK?
    >
    > Chapter & verse?
    >


    Yes, the iterators are "random access iterators" which allows adding
    or subtracting from them.

    Other containers have other kinds of iterators, and the compiler will
    tell you when addition doesn't work. One example is std::list, whose
    iterators can be incremented and decremented, but not added to.


    Bo Persson
    Bo Persson, Oct 11, 2009
    #1
    1. Advertising

  2. Bo Persson wrote:
    > Yes, the iterators are "random access iterators" which allows adding
    > or subtracting from them.
    >
    > Other containers have other kinds of iterators, and the compiler will
    > tell you when addition doesn't work. One example is std::list, whose
    > iterators can be incremented and decremented, but not added to.


    Which has the side effect that the O(1) operation iter+1 looks rather
    funny because you have to invoke the copy constructor explicitely.


    Marcel
    Marcel Müller, Oct 11, 2009
    #2
    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. Anonymous
    Replies:
    20
    Views:
    4,268
    Pete Becker
    Mar 30, 2005
  2. Replies:
    6
    Views:
    626
    Jim Langston
    Oct 30, 2005
  3. Jason Heyes
    Replies:
    8
    Views:
    706
    Andrew Koenig
    Jan 15, 2006
  4. Christopher
    Replies:
    0
    Views:
    747
    Christopher
    Jan 13, 2009
  5. Christopher
    Replies:
    9
    Views:
    575
    Marcel Müller
    Nov 6, 2012
Loading...

Share This Page