How can I insert element into beginning of vector?

后端 未结 4 1539
天涯浪人
天涯浪人 2021-01-03 18:49

I need to insert values into the beginning of a std::vector and I need other values in this vector to be pushed to further positions for example: something adde

4条回答
  •  花落未央
    2021-01-03 19:09

    Use the std::vector::insert function accepting an iterator to the first element as a target position (iterator before which to insert the element):

    #include 
    
    int main() {
        std::vector v{ 1, 2, 3, 4, 5 };
        v.insert(v.begin(), 6);
    }
    

    Alternatively, append the element and perform the rotation to the right:

    #include 
    #include 
    
    int main() {
        std::vector v{ 1, 2, 3, 4, 5 };
        v.push_back(6);
        std::rotate(v.rbegin(), v.rbegin() + 1, v.rend());
    }
    

提交回复
热议问题