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

How to Delete Elements from a std::vector by Index?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-13 04:52:14725browse

How to Delete Elements from a std::vector by Index?

Deleting Elements from std::vector by Index

Query:

How do I delete specific elements from a std::vector based on their index values?

Approach:

To erase elements from a std::vector by index, utilize the erase function. This function requires iterators specifying the starting and ending points of the elements to be removed.

Solution:

Deleting a Single Element:

To delete a single element at a specific index, employ the following approach:

vec.erase(std::next(vec.begin(), n));

Where:

  • vec represents the std::vector.
  • n is the index of the element to be deleted (indexing starts from 0).

Deleting Multiple Elements:

For deleting multiple consecutive elements, provide an additional iterator to the erase function, defining the end point:

vec.erase(std::next(vec.begin(), startIndex), std::next(vec.begin(), endIndex));

Where:

  • vec is the std::vector.
  • startIndex is the index of the first element to be deleted.
  • endIndex is the index of the last element to be deleted (inclusive).

The above is the detailed content of How to Delete Elements from a std::vector by Index?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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