从 C++ 中的向量中弹出特定元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5768316/
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
pop a specific element off a vector in c++
提问by kamikaze_pilot
so suppose I have a vector called v and it has three elements: 1,2,3
所以假设我有一个叫做 v 的向量,它有三个元素:1,2,3
is there a way to specifically pop 2 from the vector so the resulting vector becomes
有没有办法专门从向量中弹出 2,这样得到的向量就变成了
1,3
1,3
回答by Dagang
//erase the i-th element
myvector.erase (myvector.begin() + i);
(Counting the first element in the vector as as i=0
)
(将向量中的第一个元素计算为i=0
)
回答by Ken Bloom
Assuming you're looking for the element containing the value 2
, not the value at index 2
.
假设您正在寻找包含 value 的元素2
,而不是 index 处的值2
。
#include<vector>
#include<algorithm>
int main(){
std::vector<int> a={1,2,3};
a.erase(std::find(a.begin(),a.end(),2));
}
(I used C++0x to avoid some boilerplate, but the actual use of std::find
and vector::erase
doesn't require C++0x)
(我使用的C ++ 0x,以避免一些样板,但实际使用std::find
和vector::erase
不需要的C ++ 0x)
回答by Chris A.
Also, remember to use the erase-remove idiomif you are removing multiple elements.
另外,如果您要删除多个元素,请记住使用擦除-删除习语。
回答by Christo
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
unsigned int i;
vector<unsigned int> myvector;
// set some values (from 1 to 10)
for (i=1; i<=10; i++) myvector.push_back(i);
// erase the 6th element
myvector.erase (myvector.begin()+5);
// erase the first 3 elements:
myvector.erase (myvector.begin(),myvector.begin()+3);
cout << "myvector contains:";
for (i=0; i<myvector.size(); i++)
cout << " " << myvector[i];
cout << endl;
return 0;
}