How do I erase an element from std::vector<> by index?

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);

The erase method on std::vector is overloaded, so it's probably clearer to call

vec.erase(vec.begin() + index);

when you only want to erase a single element.


template <typename T>
void remove(std::vector<T>& vec, size_t pos)
{
    std::vector<T>::iterator it = vec.begin();
    std::advance(it, pos);
    vec.erase(it);
}
链接地址: http://www.djcxy.com/p/53952.html

上一篇: 用硬编码元素初始化std :: vector最简单的方法是什么?

下一篇: 如何通过索引擦除std :: vector <>中的元素?