c++ - 返回其参数或检查 nullptr 的函数

标签 c++ c++11 c++14 c++17

我想循环一个 vector 并过滤掉所有非空指针元素。我正在寻找一个 std 函数来检查是否为 nullptr 或一个 std 函数,它实际上返回传递给它的任何内容(如 std::forward),因为空指针的计算结果为 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

最佳答案

坚持使用 std 中的内容,您可以将 std::remove_copy_ifstd::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

或者,您可以使用 remove_copy 传递 nullptr:

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

如果您真的喜欢copy_if,您可以在logical_not 上使用not_fnnot1

关于c++ - 返回其参数或检查 nullptr 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44143327/

相关文章:

c++ - 模板的条件编译

c++ - 在 O(n) 中搜索 std::map 以获取部分键

c++ - 友元函数范围和声明点

c++ - 未定义的行为和顺序点

c++ - 我可以将函数的输出参数存储到 unique_ptr 中吗?

c++ - 从传递给模板函数的内部类实例中提取外部类类型

C++ 使用具有 unique_ptr、make_unique 的已删除函数

c++ - 类继承 : Constructor and member functions of class not recognized by compiler

c++ - GraphViz:使用哪个图形库?

c++ - C++14 中的 "constexpr"