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

后端 未结 5 1281
北恋
北恋 2021-01-13 06:17

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

std::vector myVector;

   void setAt(int x         


        
5条回答
  •  佛祖请我去吃肉
    2021-01-13 07:11

    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++?

提交回复
热议问题