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

后端 未结 5 1224
北恋
北恋 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:49

    If you're looking for a java-like equivalent of the ArrayList.set() method, you can do it more closely via

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

    Much like the Java version, vector::at() will throw an exception if the vector is not large enough. Note, this makes a copy of the object (actually, two, since you're also passing by value to the function).

提交回复
热议问题