如何将元素插入向量的开头? [英] How can I insert element into beginning of vector?

查看:43
本文介绍了如何将元素插入向量的开头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将值插入到 std :: vector 的开头,并且需要将该向量中的其他值推到其他位置,例如:在向量和值的开头添加了一些内容从位置1移至2,从位置2移至3,依此类推.

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.

我该怎么做?

推荐答案

使用std :: vector :: insert 函数接受第一个元素的迭代器作为目标位置(在其之前插入元素的迭代器):

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);
}

或者,追加元素并执行旋转:

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

这篇关于如何将元素插入向量的开头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆