Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > STL container questions

Reply
Thread Tools

STL container questions

 
 
Allerdyce.John@gmail.com
Guest
Posts: n/a
 
      02-20-2006
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;

 
Reply With Quote
 
 
 
 
Ben Pope
Guest
Posts: n/a
 
      02-20-2006
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...
 
Reply With Quote
 
 
 
 
Victor Bazarov
Guest
Posts: n/a
 
      02-20-2006
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


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
a few stl container questions: allocators and comparers. sheam C++ 7 06-12-2008 10:06 AM
container inside container in stl wolverine C++ 2 07-24-2006 03:08 PM
stl questions: how can I compare 2 stl list? silverburgh.meryl@gmail.com C++ 5 04-16-2006 09:57 PM
Copy elements from one STL container to another STL container Marko.Cain.23@gmail.com C++ 4 02-16-2006 05:03 PM
STL: container's values setup by another container Maitre Bart C++ 2 02-11-2004 12:11 AM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57