Home >Backend Development >C++ >How to Remove an Element from a std::vector by Index in C ?

How to Remove an Element from a std::vector by Index in C ?

DDD
DDDOriginal
2024-12-11 20:57:15266browse

How to Remove an Element from a std::vector by Index in C  ?

Erasing an Element from a std::vector by Index

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.

Solution:

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!

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