To remove an item at a specific index from a vector in C++, you can use the erase
method of the std::vector
class.
In this example,
<vector>
and <iostream>
.vec
and initialize it with some integer values.index_to_remove
.erase
method to remove the item at the specified index. The erase
method takes an iterator pointing to the element to be removed.vec.begin() + index_to_remove
and pass it to the erase
method.#include <vector>
#include <iostream>
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};
int index_to_remove = 2;
vec.erase(vec.begin() + index_to_remove);
std::cout << "Vector after removing the item at index " << index_to_remove << ": ";
for (int val : vec) {
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
Vector after removing the item at index 2: 10 20 40 50
In this example,
<vector>
and <iostream>
.remove_at_index
that takes a reference to a vector and an index as parameters.erase
method to remove the item at the specified index, obtaining the iterator by calling vec.begin() + index
and passing it to the erase
method.vec
and initialize it with some integer values.index_to_remove
.remove_at_index
function, passing vec
and index_to_remove
as arguments.#include <vector>
#include <iostream>
void remove_at_index(std::vector<int> &vec, int index) {
if (index >= 0 && index < vec.size()) {
vec.erase(vec.begin() + index);
}
}
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50};
int index_to_remove = 2;
remove_at_index(vec, index_to_remove);
std::cout << "Vector after removing the item at index " << index_to_remove << ": ";
for (int val : vec) {
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
Vector after removing the item at index 2: 10 20 40 50
In this tutorial, we learned How to Remove Item at a Specific Index from a Vector in C++ language with well detailed examples.