本文介绍了如何从std :: vector<>中删除元素按索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个std :: vector< int>,我想删除第n个元素。我该怎么做?
I have a std::vector<int>, and I want to delete the n'th element. How do I do that?
std::vector<int> vec;
vec.push_back(6);
vec.push_back(-17);
vec.push_back(12);
vec.erase(???);
推荐答案
要删除单个元素,您可以执行以下操作:
To delete a single element, you could do:
std::vector<int> vec;
vec.push_back(6);
vec.push_back(-17);
vec.push_back(12);
// Deletes the second element (vec[1])
vec.erase(vec.begin() + 1);
或者,一次删除多个元素:
Or, to delete more than one element at once:
// Deletes the second through third elements (vec[1], vec[2])
vec.erase(vec.begin() + 1, vec.begin() + 3);
这篇关于如何从std :: vector<>中删除元素按索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!