3

Im learning the C++ lambda functions, this likely easy problem is giving me some issues.

I have a vector with some integers in it. I am trying to remove all of the even numbers.

I currently have it removing the even numbers, but when I print the contents of the vector, I am left with some repeated data still in the vector at the end.

int main()
{
  std::vector<int> v1 = {0,1,1,2,3,5,8,13,21,55,89};

  for (const auto &i : v1) std::cout<< i << " ";
  std::cout<<std::endl; 

  v1.erase(std::remove_if(v1.begin(), v1.end(), [](int i)
       { return (i % 2) == 0; }));

  for (const auto &i : v1) std::cout<< i << " ";
}

OUTPUT:

0 1 1 2 3 5 8 13 21 55 89 
1 1 3 5 13 21 55 89 55 89

I want the output on the 2nd line to be:

1 1 3 5 13 21 55 89

EDIT

Thanks Everyone. I was using the wrong version of erase (feel very dumb now). Here is the correct code:

int main()
{
  std::vector<int> v1 = {0,1,1,2,3,5,8,13,21,55,89};

  for (const auto &i : v1) std::cout<< i << " ";
  std::cout<<std::endl; 

  v1.erase(std::remove_if(v1.begin(), v1.end(), [](int i)
       { return (i % 2) == 0; }), v1.end());

  for (const auto &i : v1) std::cout<< i << " ";
}
1
  • 5
    Look at which version of erase you're calling.
    – chris
    Oct 9, 2013 at 21:42

1 Answer 1

6

You're using the overload of std::vector::erase that takes a single iterator.

This is the desired overload:

iterator erase(const_iterator first, const_iterator last);

What you're aiming to do is this:

auto is_even = [](int i) { return (i % 2) == 0; };
v1.erase(std::remove_if(v1.begin(), v1.end(), is_even), v1.end());

This overload will erase the elements between first and last.

std::remove_if modifies the range so that it only contains elements that do not satisfy the condition defined by the predicate function. It then returns an iterator to the new end of the range.

Erase finishes the job by actually deleting the elements from the container.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.