[C++] while or for find_if 函数对象 lambda

while for 选哪个

while

template
In find(In first, In last, const T& val)
{
    while(first!=last && *first!=val) ++first;
    return first;
}

for

template
In find(In first, In last, const T& val)
{
    for(In p = first; p != last; ++p)
        if(*p == val) return p;
    return last;
}
  • 优先选while,因为for多个p,有些编译器不知道怎么销毁这个 p

find_if

template
In find_if(In first, In last, Pred pred)
{
    while(first!=last && !pred(*first)) ++first;
    return first;
}

bool odd(int x) { return x%2;}

void f(vector& v)
{
    auto p = find_if(v.begin(), v.end(), odd);
    if(p!=v.end()) {
        // ...
    }
}
  • 做参数传递时,不要加上(), auto p = find_if(v.begin(), v.end(), odd); ;
  • 如果写odd(),带上了括号就会调用这个函数;

函数对象

template
In find_if(In first, In last, Pred pred)
{
    while(first!=last && !pred(*first)) ++first;
    return first;
}


void f(list& v, int x)
{
    auto p = find_if(v.begin(), v.end(), Larger_than(31));
    if(p!=v.end()) {}
    
    auto q = find_if(v.begin(), v.end(), Larger_than(x));
    if(q!=v.end()) {}
}

class Larger_than{
    int v;
public:
    Larger_than(int vv): v{vv} {}
    bool operator()(int x) const { return x > v; }
};

// lambda
void f(list& v, int x)
{
    auto p = find_if(v.begin(), v.end(), [](double a) { return a > 31;});
    if(p!=v.end()) {}
    
    auto q = find_if(v.begin(), v.end(), [&](double a) { return a > x;});
    if(q!=v.end()) {}
}
  • Larger_than(31) 初始化了一个类对象,甚至v31
  • pred(*first) ,在这里会被解释成Larger_than(*first),是因为我们定义了bool operator()(int x) const { },此处x就是*first;

Programming -- Principles and Practice Using C++ (Second Edition)
http://www.stroustrup.com/Programming/

你可能感兴趣的:([C++] while or for find_if 函数对象 lambda)