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
Release: 2024-12-13 04:52:14
Original
757 people have browsed it

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

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

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!

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