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

后端 未结 5 1277
北恋
北恋 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 06:55

    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

提交回复
热议问题