C++ の any_of は find_if とほぼ一緒2020年05月21日 20時54分43秒

find_if はまあ必須な関数。algorithm ライブラリの中で面白いなと思ったのが、any_of 関数。

find_if はイテレータを返すが、any_of は真偽値を返す。any_of は find_if とほぼ同等で、真偽値の判別に特化した関数の様だ。find_if で代用可能な関数が find_if より後の C++11 で追加された。

折角なので、find_if と any_of で同じことをやってみる。

#include <vector>
#include <iostream>
#include <algorithm>

int main()
{
    auto negative = []( int i ){ return i < 0; };

    std::vector< int > ones = { 1, 2, 3, 4, -2,  5, 0, -1 };

    auto any = std::any_of( ones.begin(), ones.end(), negative );
    auto find = std::find_if( ones.begin(), ones.end(), negative );

    std::cout << "any_of returned " << any << std::endl;
    std::cout << "find_if returned " << *find << std::endl;
}
find_if はイテレータを返すので値を出力。
% ./a.out 
any_of returned 1
find_if returned -2
真偽値が欲しければ、ones.end() と比較する。

前回