-1

So i'm supposed to Move all palindrome numbers from mValues vector to mPalindromes vector

and the only hints I was given was a pseudo code: // iterate through the main values vector // if the value is a palindrome // add it to the palindrome vector // remove it from the values vector

and this is what I came up with:

for (int i = 0; i < mValues.size(); i++)
    {
        if (IsPalindromeNumber(mValues[i]) )
        {
            mPalindromes.push_back(mValues[i]);

            mValues.pop_back();

            
        }
    }

If anyone could tell me where I went wrong I would appreciate it.

edit: I figured it out the problem was I was using erase instead of popback.

Neteroh
  • 7
  • 4

1 Answers1

2

When you do

mValues.erase(mValues.begin() + i); // with correction from comments

you modify mValues, so i starts indexing elsewhere in mValues. One fix would be

mValues.erase(mValues.begin() + i);
i--;

but it's not very elegant. It would be better to copy the palindromes to mPalindromes and then use std::remove_if or something, in a second pass.

Jeffrey
  • 11,063
  • 1
  • 21
  • 42
  • 4
    Hmm... If only there were some [combination of `copy` and `remove_if`](https://en.cppreference.com/w/cpp/algorithm/remove_copy) :) – chris Jul 10 '20 at 02:39