Question about C++ vectors.

What is the correct way to put data into (or take it out of a vector)?

Lets say I have a vactor.
vector<int> MyVect(5);

To put something into it should I use standard array notation like this?
MyVect[0] = 123;

Or should I use the vector's "at" keyword like this?
MyVect.at(0) = 123;

And same thing for getting a number back out of the vector. Should I use the standard array notation, or should I use the vector's "at" keyword?
If you know that the position is valid ie. 0 <= pos < my_vect.size() use my_vect[pos]

If not, use the keyword member function at() for bounds checked access my_vect.at(pos)

To add a new element at the end of the sequence, use push_back() or emplace_back()
at() does bounds checking and will throw an exception if you access an out of bounds element.
The [] operator does not.

So at() is slower but safer.
Whereas [] is faster but less safe.



That being said, I pretty much use [] all the time.
Topic archived. No new replies allowed.