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
Release: 2024-12-11 20:57:15
Original
263 people have browsed it

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template