Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ lambda remove even numbers

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 << " ";
}
like image 783
r-s Avatar asked Mar 04 '26 12:03

r-s


1 Answers

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.

like image 173
user123 Avatar answered Mar 06 '26 01:03

user123