您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

理解bind1st和bind2nd函数

2026/2/4 20:38:13发布6次查看
值(v)是一个固定的参数。换言之,uf(x)等价于: bf( x, v) 当使用bind2nd时 bf( v, x) 当使用bind1st时 bind1st 和 bind2nd 函数在处理谓词时非常有用。它们使得二元谓词能够转换成一元谓词;这常用于将一个范围内的所有值与一个特定的值比较: std::vecto
值(v)是一个固定的参数。换言之,uf(x)等价于:
bf( x, v) – 当使用bind2nd时 bf( v, x) – 当使用bind1st时 bind1st和bind2nd函数在处理谓词时非常有用。它们使得二元谓词能够转换成一元谓词;这常用于将一个范围内的所有值与一个特定的值比较:
std::vector a;
// ……填充a
// 移除所有小于30的元素
a.erase( std::remove_if( a.begin(), a.end(),
    std::bind2nd( std::less(), 30)), a.end());
在大多数时候,bind2nd就足够了,像上面的例子。不管怎样,在进行泛型编程时,你会实现一些处理谓词的函数。谓词指定了范围内的排序准则,通常是“)。记住你可以仅用一个给定的“”运算符。这时你会发现bind1st和bind2nd都能用上。
#include
#include
#include
template
    void for_each_if( iterator itfirst, iterator itlast, predicate pred, doer do_it)
{
    while ( itfirst != itlast)
    {
        if ( pred( *itfirst)) do_it( *itfirst);
        ++itfirst;
    }
}
void print( int i) { std::cout
int main(int argc, char* argv[])
{
    int anumbers[] = { 10, 5, 89, 9, 30, -2, -8, 7, 33, 25, 30, 76, 0, 2};
    int ncount = sizeof( anumbers) / sizeof( anumbers[ 0]);
// a     std::cout     for_each_if( anumbers, anumbers + ncount,
        std::bind2nd( std::less(), 30), print);
    std::cout     // a > b
    for_each_if( anumbers, anumbers + ncount,
        std::bind1st( std::less(), 30), print);
    std::cout     // a      !(a > b)
    for_each_if( anumbers, anumbers + ncount,
        std::not1( std::bind1st( std::less(), 30)), print);
    std::cout     // a >= b           !(a     for_each_if( anumbers, anumbers + ncount,
        std::not1( std::bind2nd( std::less(), 30)), print);
    return 0;
}
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product