STL container questions

A

Allerdyce.John

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;
 
B

Ben Pope

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
 
V

Victor Bazarov

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top