如何从 std::vector<> 中擦除元素按索引?

2021-12-21 00:00:00 vector c++ stl erase

我有一个 std::vector,我想删除第 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(std::next(vec.begin()));

或者,一次删除多个元素:

Or, to delete more than one element at once:

// Deletes the second through third elements (vec[1], vec[2])
vec.erase(std::next(vec.begin(), 1), std::next(vec.begin(), 3));

相关文章