美文网首页
C++ STL std::ptr_fun() 函数说明

C++ STL std::ptr_fun() 函数说明

作者: book_02 | 来源:发表于2019-06-28 20:44 被阅读0次

说明

将一个普通函数包装成函数对象。

此函数与关联类型从 C++11 起被弃用,被更通用的 std::function 和 std::ref 所替代。

头文件

#include <functional>

例子

#include <string>
#include <iostream>
#include <algorithm>
#include <functional>
 
bool isvowel(char c)
{
    return std::string("aeoiuAEIOU").find(c) != std::string::npos;
}
 
int main()
{
    std::string s = "Hello, world!";
    std::copy_if(s.begin(), s.end(), std::ostreambuf_iterator<char>(std::cout),
                 std::not1(std::ptr_fun(isvowel)));
}

结果:

Hll, wrld!

上面的例子是把isvowel通过ptr_fun包装成函数对象传给std::not1().

C++11 替用方案 :
可将 std::not1(std::ptr_fun(isvowel)) 改为 std::not1(std::cref(isvowel)) 或者 std::not1(std::function<bool(char)>(isvowel))

参考

https://zh.cppreference.com/w/cpp/utility/functional/ptr_fun
http://www.cplusplus.com/reference/functional/ptr_fun/

相关文章

网友评论

      本文标题:C++ STL std::ptr_fun() 函数说明

      本文链接:https://www.haomeiwen.com/subject/mtcycctx.html