Removing elements from vector using remove_if

  • A+
Category:Languages

I am trying to remove vector elements using remove_if. But unsuccessfully. What am I doing wrong?

Here's my code:

#include <iostream> #include <string> #include <vector> #include <algorithm>  void printme(std::vector<int>& a){     for(const auto& item: a)     std::cout << item << std::endl; }  int main() {     std::vector<int> a {1, 2, 3, 4, 5, 6};     printme(a);       a.erase( (std::remove_if(a.begin(), a.end(), [](const int& x){         return x == 2;         }), a.end()));     printme(a); } 

My output is just:

1 2 3 4 5 6

Expected output:

1 2 3 4 5 6 1 3 4 5 6

 


You are using an overload of the std::vector::erase() member function that takes a single iterator as parameter. As the argument to erase() you are providing the iterator a.end(), since the following expression:

(std::remove_if(a.begin(), a.end(), [](const int& x){ return x == 2; }), a.end())) 

evaluates to a.end() (i.e., because of the comma operator).

The iterator passed to the overload of erase() that takes a single iterator must be dereferenceable. However, the iterator a.end() is not dereferenceable, therefore, the call to erase() results in undefined behavior.


To use the overload that takes two iterators, remove the parenthesis surrounding the call to std::remove_if:

a.erase(std::remove_if(a.begin(), a.end(), [](const int& x){         return x == 2;         }), a.end()); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: