C
C
Clean Coder2019-02-22 11:58:51
C++ / C#
Clean Coder, 2019-02-22 11:58:51

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

1 answer(s)
A
Adamos, 2019-02-22
@HustleCoder

Change for to while and in case of deletion
iter = mas.erase(iter);
otherwise
iter++;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question