Insert into std :: vector by index via assignment operator

I am new to C ++ and I wonder if this is the preferred way to insert into 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 usage push_back, or in a very confusing way insert(). Is this Java method similar? I would rather do it ...

+5
source share
5 answers
myVector[x] = o;

It is correctly defined only if x < myVector.size(). Otherwise, it calls undefined -behavior, because in this case it is trying to access the element from the border of the vector.

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

myVector.at(x) = o;

std::out_of_range, x >= myVector.size(). , try-catch! .

+10

myVector[x] = o - myVector.push_back(o) ( insert). , , :

  • myVector[x] = o , x o. vector , , x, vector. myVector , x, , undefined
  • myVector.push_back(o) o myVector. vector , myVector o. myVector.
  • myVector.insert(i, o) o , i. , "ith" ( myVector.begin() - i) o
+2

, x + 1. , .

:

std::vector<Object_I_madeup> myVector(10); // construct the vector with size 10
                                           // and default-initialize its elements

0 - 9. , .

+1

It will work if you are not trying to access it from your borders, i.e. the size of the vector is larger than x.

+1
source

If you are looking for a java-like equivalent of a method ArrayList.set(), you can do it more closely with

void setAt(int x, Object_I_madeup o)
{
    myVector.at(x) = o;
}

Like the Java version, it vector::at()will throw an exception if the vector is not large enough. Note that this makes a copy of the object (in fact, two, since you also pass the value of the function).

+1
source

All Articles