STL container questions

Discussion in 'C++' started by Allerdyce.John@gmail.com, Feb 20, 2006.

  1. Guest

    Hi,

    What will happen if i access an element which is bigger than the
    container?
    e.g.
    vector<int> aVector(1);
    cout << aVector[6] << endl?
    // or can I do this:
    aVector[6] = 3;

    How about a Map?
    map<int, int> aMap(1);
    aMap[2] = 1;
    aMap[1] = 2;
    , Feb 20, 2006
    #1
    1. Advertising

  2. Ben Pope Guest

    wrote:
    > Hi,
    >
    > What will happen if i access an element which is bigger than the
    > container?
    > e.g.
    > vector<int> aVector(1);
    > cout << aVector[6] << endl?


    /the above line causes undefined behaviour, ANYTHING could happen from
    now one.

    > // or can I do this:
    > aVector[6] = 3;


    //Same as above

    > How about a Map?
    > map<int, int> aMap(1);
    > aMap[2] = 1;
    > aMap[1] = 2;


    No, they are both fine, assuming you remove the UB above.

    What book are you reading that does not discuss this?

    Ben Pope
    --
    I'm not just a number. To many, I'm known as a string...
    Ben Pope, Feb 20, 2006
    #2
    1. Advertising

  3. wrote:
    > What will happen if i access an element which is bigger than the
    > container?


    Usually the behaviour is undefined. If you use .at() instead of
    the indexing, then 'vector' throws and you can catch the exception.

    > e.g.
    > vector<int> aVector(1);
    > cout << aVector[6] << endl?
    > // or can I do this:
    > aVector[6] = 3;


    The behaviour is undefined.

    > How about a Map?
    > map<int, int> aMap(1);
    > aMap[2] = 1;
    > aMap[1] = 2;


    'std::map' actually inserts if the element doesn't exist.

    V
    --
    Please remove capital As from my address when replying by mail
    Victor Bazarov, Feb 20, 2006
    #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. Maitre Bart
    Replies:
    2
    Views:
    521
    Maitre Bart
    Feb 11, 2004
  2. Replies:
    4
    Views:
    798
    Daniel T.
    Feb 16, 2006
  3. Replies:
    5
    Views:
    503
    Markus Schoder
    Apr 16, 2006
  4. wolverine
    Replies:
    2
    Views:
    450
    Marcus Kwok
    Jul 24, 2006
  5. sheam
    Replies:
    7
    Views:
    337
    Frank Birbacher
    Jun 12, 2008
Loading...

Share This Page