Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using std::remove to delete pointer elements

Tags:

c++

I'm trying to do

remove(pvec.begin(), pvec.end(), NULL);

to remove NULL pointers in the vector (where pvec is vector<Node*>)

However, the compiler gives:

"ISO C++ forbids comparison between pointer and integer"

How to resolve this? Thanks!

like image 1000
JASON Avatar asked Jun 16 '13 00:06

JASON


People also ask

How do you delete a pointer variable in C++?

delete and free() in C++ In C++, the delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer. It is an operator.

Does erase delete pointer?

Yes. vector::erase destroys the removed object, which involves calling its destructor.


1 Answers

In C++11, use nullptr:

remove(pvec.begin(), pvec.end(), nullptr);
//                               ^^^^^^^

Otherwise, perform an explicit cast to a pointer value. If your pvec contains pointers of type foo*, write:

remove(pvec.begin(), pvec.end(), static_cast<foo*>(NULL));
//                               ^^^^^^^^^^^^^^^^^
like image 189
Andy Prowl Avatar answered Oct 28 '22 07:10

Andy Prowl