How can I insert element into beginning of vector?

喜夏-厌秋 提交于 2020-03-14 06:55:31

问题


i'm newbie in writing code and i need a little help.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 added to beginning of a vector and values moved from position 1 to 2, from 2 to 3 etc. how do i do that?


回答1:


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

#include <vector>

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

Edit: As pointed out in the comments, you could also append the element and perform the rotation to the right:

#include <vector>
#include <algorithm>

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



回答2:


You should consider using std::deque. It works alot like a std::vector but you can add and remove items from both the front and the end.

It does this by dividing the internal storage up into smaller blocks. You still have random-access iterators with good lookup speed.

If your container is small it should be fine to use the std::vector approach but if you are storing large amounts of data the std::deques performance for inserting/deleting at the front will be far superior.



来源:https://stackoverflow.com/questions/48251254/how-can-i-insert-element-into-beginning-of-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!