Home >Backend Development >C++ >How to Remove an Element from a std::vector by Index in C ?
In C , when working with a std::vector, there may be instances where removing an element by its index is necessary.
Consider a scenario where you have a vector of integers and need to delete the nth element.
To delete a single element at position n, simply use std::erase with an iterator to the desired position. Here's how you would do it:
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()));
std::next(vec.begin()) returns an iterator to the second element, which is then erased.
If you want to delete multiple consecutive elements, use erase with a range of iterators:
// Deletes the second through third elements (vec[1], vec[2]) vec.erase(std::next(vec.begin(), 1), std::next(vec.begin(), 3));
The above is the detailed content of How to Remove an Element from a std::vector by Index in C ?. For more information, please follow other related articles on the PHP Chinese website!