remove nth element from vector c++ code example
Example 1: remove element by index from vector c++
vec.erase(vec.begin() + 1);
vec.erase(vec.begin() + 1, vec.begin() + 3);
Example 2: vector erase specific element
vector.erase( vector.begin() + 3 );
Example 3: removing element from vector while iterating c++
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5, 6 };
auto it = v.begin();
while (it != v.end())
{
if (*it & 1) {
it = v.erase(it);
}
else {
++it;
}
}
for (int const &i: v) {
std::cout << i << ' ';
}
return 0;
}
Example 4: vector erase specific element
template <typename T>
void remove(std::vector<T>& vec, size_t pos)
{
std::vector<T>::iterator it = vec.begin();
std::advance(it, pos);
vec.erase(it);
}