Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function returning its argument or checking for nullptr

I would like to loop on a vector and filter out all the non-null-pointer elements. I'm looking for either an std function that checks for something being a nullptr or an std function that actually returns whatever is passed to it (like std::forward), since a null pointer would evaluate to false.

std::copy_if(dynamicObjects.begin(), dynamicObjects.end(),
    std::back_inserter(existingObjects), 
    std::is_pointer<ObjectType*>); // This does not compile

std::copy_if(dynamicObjects.begin(), dynamicObjects.end(),
    std::back_inserter(existingObjects), 
    std::forward<ObjectType*>); // This does not compile either

std::copy_if(dynamicObjects.begin(), dynamicObjects.end(),
    std::back_inserter(existingObjects), 
    static_cast<bool>); // This won't help me :)

std::copy_if(dynamicObjects.begin(), dynamicObjects.end(),
    std::back_inserter(existingObjects), 
    [] (const auto a) { return a; } ); // This is awkward
like image 743
Adam Hunyadi Avatar asked Nov 29 '25 11:11

Adam Hunyadi


1 Answers

Stuck with the stuff in std, you can use std::remove_copy_if with std::logical_not.

std::remove_copy_if(dynamicObjects.begin(), dynamicObjects.end(),
    std::back_inserter(existingObjects), 
    std::logical_not<ObjectType*>()); // or std::logical_not<> in C++14

Or, you can use remove_copy passing nullptr:

std::remove_copy(dynamicObjects.begin(), dynamicObjects.end(),
    std::back_inserter(existingObjects), 
    nullptr);

If you really like copy_if, you can use not_fn or not1 on the logical_not instead.

like image 120
T.C. Avatar answered Nov 30 '25 23:11

T.C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!