Deleting Elements from std::vector by Index
One common task in programming is deleting elements from a container, such as a vector. std::vector is a dynamic array in C that allows efficient insertion and deletion of elements. Deleting an element by index can be achieved in several ways.
Deleting a Single Element
To delete a single element from a vector, use the erase() function. This function takes an iterator to the element to be deleted. For instance:
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()));
The std::next() function is used to advance the iterator to the desired index.
Deleting Multiple Elements
To delete multiple elements at once, use the erase() function with an iterator range. The range is specified by two iterators: one pointing to the first element to be removed and the other pointing to the element just past the last one to be removed. For example:
// 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 Do I Efficiently Delete Elements from a C std::vector by Index?. For more information, please follow other related articles on the PHP Chinese website!