Home >Database >Mysql Tutorial >理解bind1st和bind2nd函数

理解bind1st和bind2nd函数

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-07 15:30:311710browse

值(v)是一个固定的参数。换言之,uf(x)等价于: bf( x, v) 当使用bind2nd时 bf( v, x) 当使用bind1st时 bind1st 和 bind2nd 函数在处理谓词时非常有用。它们使得二元谓词能够转换成一元谓词;这常用于将一个范围内的所有值与一个特定的值比较: std::vecto

理解bind1st和bind2nd函数

值(v)是一个固定的参数。换言之,uf(x)等价于:

  • bf( x, v) – 当使用bind2nd时
  • bf( v, x) – 当使用bind1st时

bind1stbind2nd函数在处理谓词时非常有用。它们使得二元谓词能够转换成一元谓词;这常用于将一个范围内的所有值与一个特定的值比较:

std::vector a;
// ……填充a

// 移除所有小于30的元素
a.erase( std::remove_if( a.begin(), a.end(),
    std::bind2nd( std::less(), 30)), a.end());

在大多数时候,bind2nd就足够了,像上面的例子。不管怎样,在进行泛型编程时,你会实现一些处理谓词的函数。谓词指定了范围内的排序准则,通常是“)。记住你可以仅用一个给定的“”运算符。这时你会发现bind1stbind2nd都能用上。

#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;
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn