Answer the question
In order to leave comments, you need to log in
Removing elements from a vector (STL). Where is the mistake?
I set an array of integers, I want to remove all zeros from it. I use the erase function for this. Since all elements are moved when deleting, I return the iterator one step back (iter--). Why doesn't it work like this and what is the right way to remove arbitrary elements from a vector? (Or is there anyway to use another container?)
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> mas;
vector<int>::iterator iter;
int N{0}, temp{0};
cout << "An array's size - ";
cin >> N;
for(int i = 0; i < N; ++i)
{
cin >> temp;
mas.push_back(temp);
}
for(iter = mas.begin(); iter != mas.end(); ++iter)
{
if (*iter == 0)
{
mas.erase(iter);
iter--;
}
}
for(iter = mas.begin(); iter != mas.end(); ++iter)
{
cout << *iter << " ";
}
return 0;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question