我需要将值插入到 std::vector
的开头,并且我需要将此 vector 中的其他值推到更远的位置,例如:添加到 vector 开头的内容和值从位置 1 移动到位置 2,从位置 2 移动到位置 3 等等。
我该怎么做?
最佳答案
使用 std::vector::insert接受 iterator to the first 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());
}
关于c++ - 如何将元素插入 vector 的开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48251254/