Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

c++ - How can I insert element into beginning of vector?

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 can I do that?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 <vector>

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

Alternatively, 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());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...