Home > Backend Development > C++ > How Do I Efficiently Delete Elements from a C std::vector by Index?

How Do I Efficiently Delete Elements from a C std::vector by Index?

Mary-Kate Olsen
Release: 2024-12-17 01:58:25
Original
146 people have browsed it

How Do I Efficiently Delete Elements from a C   std::vector by Index?

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()));
Copy after login

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));
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template