findとfind_ifアルゴリズム

3350 ワード

1、STLアルゴリズムのfindとfind_ifアルゴリズムの使用:
連絡と区別:連絡:この2つの関数はいずれも要素の位置を検索する方法です.違い:find値は、その内側の要素値を検索する場所に適しています.そしてfind_if値は関数の3番目のパラメータと判別式の場合の使用を用いる.
template
InputIterator find ( InputIterator first, InputIterator last, const T& value )
{
for ( ;first!=last; first++) if ( *first==value ) break;
return first;
}

区間[first,end)の最初の値がvalueの要素に等しい位置を返します.
一致する要素が見つからない場合はendを返します.
複雑度:線形複雑度.最大比較回数は、要素の合計数です.
プログラムの例:
次のプログラムはintタイプのvectorで要素5と12を検索し、検索したらその位置ifオーサーに戻ってヒント情報を出力します.
main.cpp(ヘッダファイルalgostuff.hは前のブログと同じ):
#include "algostuff.h"
using namespace std;
int main()
{
vector intVec;
INSERT_ELEMENTS(intVec,1,9);
vector::iterator pos;
pos = find(intVec.begin(),intVec.end(),5);
if(pos != intVec.end())
cout << "The value 5 exists,and its position is " <<
distance(intVec.begin(),pos) + 1 << endl;
else
cout << "The value 4 not found!" << endl;
pos = find(intVec.begin(),intVec.end(),12);
if(pos != intVec.end())
cout << "The value 12 exists,and its position is " <<
distance(intVec.begin(),pos) + 1 << endl;
else
cout << "The value 12 not found!" << endl;
}

 
二、find_if()アルゴリズム
template
InputIterator find_if ( InputIterator first, InputIterator last, Predicate pred )
{
for ( ; first!=last ; first++ ) if ( pred(*first) ) break;
return first;
}

区間[first,end)で一元判定式predをtrueとする最初の要素を検索する.
見つからなかったらendに戻ります.
プログラムの例:
次のプログラムは、3で除去できる最初の要素を見つけ、その位置を返すとします.
main.cpp:

#include "algostuff.h"
using namespace std;
int main()
{
vector intVec;
INSERT_ELEMENTS(intVec,1,9);
vector::iterator pos;
pos = find_if(intVec.begin(),intVec.end(),
not1(bind2nd(modulus(),3)));
if(pos != intVec.end())
cout << "The value divided by 3 exists,and the first value's position is " <<
distance(intVec.begin(),pos) + 1 << endl;
else
cout << "The value divided by 3 not found!" << endl;
}

 
もう1つの使用例は、
    
                    // add old tracked objects
                        for (auto &i : old_result_vec) {
                            auto it = std::find_if(result_vec.begin(), result_vec.end(),
                                [&i](bbox_t const& b) { return b.track_id == i.track_id && b.obj_id == i.obj_id; });
                            //         end(),       。
                            bool track_id_absent = (it == result_vec.end());
                            if (track_id_absent) {
                                //   -->           ,                
                                if (i.frames_counter-- > 1)
                                    result_vec.push_back(i);
                            }
                            else {
                                //  box          ,   3 
                                it->frames_counter = std::min((unsigned)3, i.frames_counter + 1);
                            }
                        }

 

原文:https://blog.csdn.net/yangdashi888/article/details/80986075