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(???);
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(???);
If you have an unordered vector you can take advantage of the fact that it's unordered and use something I saw from Dan Higgins at CPPCON
Since the list order doesn't matter, just take the last element in the list and copy it over the top of the item you want to remove, then pop and delete the last item.
The previous answers assume that you always have a signed index. Sadly,
std::vector
usessize_type
for indexing, anddifference_type
for iterator arithmetic, so they don't work together if you have "-Wconversion" and friends enabled. This is another way to answer the question, while being able to handle both signed and unsigned:To remove:
To take:
Actually, the
erase
function works for two profiles:Removing a single element
Removing a range of elements
Since std::vec.begin() marks the start of container and if we want to delete the ith element in our vector, we can use:
If you look closely, vec.begin() is just a pointer to the starting position of our vector and adding the value of i to it increments the pointer to i position, so instead we can access the pointer to the ith element by:
So we can write:
To delete an element use the following way:
For a more broad overview you can visit: http://www.cplusplus.com/reference/vector/vector/erase/
The
erase
method will be used in two ways:Erasing single element:
Erasing range of elements:
To delete a single element, you could do:
Or, to delete more than one element at once: