提问人:Sengiley 提问时间:6/25/2022 更新时间:6/25/2022 访问量:715
从 std::vector 中选择除一个具有给定索引的元素之外的所有元素?
Select all elements but one with given index from std::vector?
问:
给定一个 std::vector,例如 ints
std::vector vec{10, 20, 30}
如何选择除给定索引之外的所有项目,例如结果int i=1
std::vector {10, 30}
?
答:
1赞
Ernesto Valencia
6/25/2022
#1
如果您只想从原始向量中“选择”值,我将创建另一个包含所有新值的向量。
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vect{ 10, 20, 30 };
vector<int> selected;
int i = 1;
for (int j = 0; j < vect.size(); j++) {
if (j != i) {
selected.push_back(vect[j]);
}
}
// Added so you can check the new values
for (int z = 0; z < selected.size(); z++) {
cout << selected[z] << " ";
}
return 0;
}
但是,如果您想从原始向量中删除值,我建议使用 vector.erase 方法(研究文档)。
评论
0赞
HolyBlackCat
6/25/2022
我会补充..reserve()
1赞
gouravm
6/25/2022
#2
这是一个函数,您可以在其中传递向量和索引,它将返回没有该索引元素的新向量。
#include <iostream>
#include <vector>
using namespace std;
// returns a new vector without the v[index]
vector<int> getElementsExceptIndex(vector<int> v, int index){
vector<int> newVector;
for(auto &x:v ){
if(( &x - &v[0]) != index)
newVector.push_back(x);
}
return newVector;
}
int main() {
vector<int> originalVector{ 10, 20, 30 ,33,53};
int index=1;
auto RemovedIndexVector = getElementsExceptIndex(originalVector,index);
for(auto item:RemovedIndexVector)
cout<<item<<" ";
return 0;
}
// Output - 10 30 33 53
希望这会有所帮助
评论
vec.erase(vec.begin() + i)
.如果需要新的向量,只需复制原始向量并执行擦除操作即可。