Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting into a std::vector at an index via the assignment operator

Tags:

c++

stdvector

I'm new to C++ and am curious if this is the preferred way of inserting into a std::vector

std::vector<Object_I_madeup> myVector;

   void setAt(int x, Object_I_madeup o)
        {
            myVector[x] = o;

        } // set the array location at x  to be o.

I ask because I see a lot of things about using push_back,or the highly confusing insert(). Is this Java-like way valid? I'd much rather do that...

like image 289
PinkElephantsOnParade Avatar asked Aug 30 '12 19:08

PinkElephantsOnParade


2 Answers

myVector[x] = o;

It is well-defined only if x < myVector.size(). Otherwise, it invokes undefined-behavior, because in that case it attempts to access an element out of the bound of the vector.

If you want to make sure that it checks for out-of-bound-access also, then use at() as:

myVector.at(x) = o;

Now it will throw std::out_of_range exception if x >= myVector.size(). So you have to put this code in try-catch block! The difference between them is discussed at great detail here.

  • Why is using "vector.at(x)" better than "vector[x]" in C++?
like image 131
Nawaz Avatar answered Sep 18 '22 10:09

Nawaz


myVector[x] = o does something completely different from using myVector.push_back(o) (or using insert). Therefore which method is correct depends on what you are trying to do:

  • myVector[x] = o doesn't insert in the vector, but replaces the element at position x with o. Therefore the length of the vector doesn't change and the value which was previously at position x isn't in the vector any more. If the length of myVector wasn't bigger then x this will result in an out of bounds access, leading to undefined behaviour
  • myVector.push_back(o) will insert o at the end of myVector. Therefore after this operation the length of the vector will be increased by one and the last element of myVector will be o. No values have been removed from myVector.
  • myVector.insert(i, o) will insert o at an arbitrary position, specified by the iterator i. Therefore the length of the vector will be increased by one and the "ith" element (element number myVector.begin() - i) will be o
like image 26
Grizzly Avatar answered Sep 20 '22 10:09

Grizzly