How do I erase elements of vector<> with an index?

Asked 2 years ago, Updated 2 years ago, 78 views

How do I erase the nth element in std::vector? How do I write functions such as erase() in the source code below?

std::vector<int> vec;

vec.push_back(6);
vec.push_back(-17);
vec.push_back(12);

vec.erase(???); //// How do I do this???

c++ stl vector erase

2022-09-22 13:05

1 Answers

std::vector<int> vec;

vec.push_back(6);
vec.push_back(-17);
vec.push_back(12);

// Clear the second element (vec[1])
vec.erase(vec.begin() + 1);
// Erase 2nd to 3rd elements (vec[1], vec[2])
vec.erase(vec.begin() + 1, vec.begin() + 3);


2022-09-22 13:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.