我想循环一个 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_if
与 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
或者,您可以使用 remove_copy
传递 nullptr
:
std::remove_copy(dynamicObjects.begin(), dynamicObjects.end(),
std::back_inserter(existingObjects),
nullptr);
如果您真的喜欢copy_if
,您可以在logical_not
上使用not_fn
或not1
。
关于c++ - 返回其参数或检查 nullptr 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44143327/