C++ 如何将元素插入到向量的开头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48251254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I insert element into beginning of vector?
提问by Pawe? Szymkowicz
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?
我是编写代码的新手,我需要一点帮助。我需要将值插入到 a 的开头,std::vector
我需要将此向量中的其他值推到更远的位置,例如:添加到向量和值开头的内容从位置 1 移动到 2,从 2 移动到 3 等等。我该怎么做?
回答by Ron
Use std::vector::insertfunction accepting iterator to the first elementas a target position (iterator before which to insert the element):
使用std::vector::insert函数接受第一个元素的迭代器作为目标位置(在其之前插入元素的迭代器):
#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 appendthe element and perform the rotationto 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());
}
回答by super
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.
您应该考虑使用std::deque
. 它的工作原理很像 a,std::vector
但您可以从前端和后端添加和删除项目。
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::deque
s performance for inserting/deleting at the front will be far superior.
如果您的容器很小,使用这种std::vector
方法应该没问题,但是如果您存储大量数据std::deque
,则在前面插入/删除的性能会好得多。
回答by Yevhenii Mamontov
You can insert values to std::vector
from back and then use std::reverse
:
您可以std::vector
从后面插入值,然后使用std::reverse
:
Example:
例子:
#include <vector>
#include <algorhitm>
#include <iostream>
void printVector( std::vector< int > const & _vector )
{
for( auto value : _vector )
{
std::cout << value << " ";
}
std::cout << std::endl;
}
int main()
{
std::vector< int > someVec;
someVec.push_back( 5 );
someVec.push_back( 4 );
someVec.push_back( 3 );
someVec.push_back( 2 );
someVec.push_back( 1 );
// (1)
printVector( someVec );
std::reverse( someVec.begin(), someVec.end() );
// (2)
printVector( someVec );
return 0;
}
Output (1):
输出 (1):
5 4 3 2 1
Output (2):
输出 (2):
1 2 3 4 5