Inserting into map while using iterator?

Discussion in 'C++' started by Henrik Goldman, Oct 21, 2007.

  1. Hello,

    I would like to know if it's legal to insert one or more items into a
    std::map while traversing it from begin() to end().

    E.g.

    for (it = mymap.begin(); it != mymap.end(); it++)
    {
    if (condition)
    mymap[key] = data;
    }

    Will the iterator get invalidated?

    Thanks.

    -- Henrik
    Henrik Goldman, Oct 21, 2007
    #1
    1. Advertising

  2. On 2007-10-21 15:23, Henrik Goldman wrote:
    > Hello,
    >
    > I would like to know if it's legal to insert one or more items into a
    > std::map while traversing it from begin() to end().
    >
    > E.g.
    >
    > for (it = mymap.begin(); it != mymap.end(); it++)
    > {
    > if (condition)
    > mymap[key] = data;
    > }
    >
    > Will the iterator get invalidated?



    No, inserting elements into a (multi)map/set does not invalidate
    iterators, also erasing elements only invalidates iterators to the
    deleted elements.

    --
    Erik Wikström
    =?UTF-8?B?RXJpayBXaWtzdHLDtm0=?=, Oct 21, 2007
    #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. wolverine
    Replies:
    3
    Views:
    1,056
    Chris
    Jul 31, 2006
  2. Replies:
    10
    Views:
    676
    red floyd
    Apr 3, 2007
  3. desktop
    Replies:
    12
    Views:
    630
  4. Vikram Karandikar
    Replies:
    1
    Views:
    185
    Vikram Karandikar
    Oct 25, 2013
  5. Jim Anderson

    problem with iterator (map iterator)

    Jim Anderson, Jan 10, 2014, in forum: C++
    Replies:
    3
    Views:
    108
    Luca Risolia
    Jan 13, 2014
Loading...

Share This Page