tmighty
tmighty

Reputation: 153

C++ understanding iter and erase

I am just looking at a code, and I must say that I don't fully understand it yet.

vector<long>::iterator iter1;
vector<long>::iterator iter2;

while(m_vPitchMarks[0]<=vPitchPeriode[0])
{
    iter1 = m_vPitchMarks.begin();
    iter2 = vPitchPeriode.begin();

    m_vPitchMarks.erase(iter1);
    vPitchPeriode.erase(iter2);
    if((m_vPitchMarks.size()==0)||(vPitchPeriode.size()==0))
        break;
}   

I am trying to break it down:

Here we will do a while-statement while the value of the first element of m_vPitchMarks is smaller than the value of the first element of vPitchPeriod.

while(m_vPitchMarks[0]<=vPitchPeriode[0])
{
}   

Here we set something like a reference to the first element (element at index [0]) of both vectors.

iter1 = m_vPitchMarks.begin();
iter2 = vPitchPeriode.begin();

Now we erase all elements from m_vPitchMarks<> that have just this value. For example, if iter1 had a value of 15, all elements in m_vPitchMarks<> that also have the value of 15 will be deleted, and the vector becomes shortened.

m_vPitchMarks.erase(iter1);
vPitchPeriode.erase(iter2);

Is that correct? Thank you.

Upvotes: 1

Views: 76

Answers (1)

PeterSW
PeterSW

Reputation: 5281

Almost as you say this:

while(m_vPitchMarks[0]<=vPitchPeriode[0])

will loop while the first value of m_vPitchMarks is less than or equal to the first value of vPitchPeriode.

Your explanation for this this code:

    iter1 = m_vPitchMarks.begin();
    iter2 = vPitchPeriode.begin();

    m_vPitchMarks.erase(iter1);
    vPitchPeriode.erase(iter2);

is not quite right. It simply removes the first value from both the vectors.

If you were using a std::deque or a std::list instead then you would just call pop_front to get the same result.

Then if we're out of values stop looping:

    if((m_vPitchMarks.size()==0)||(vPitchPeriode.size()==0))
        break;

Seems a particularly inefficient route given erasing an element from the front of a vector requires shifting every element that is left.

Upvotes: 2

Related Questions