泛型演算法find和find_if以及sort
阿新 • • 發佈:2019-01-24
一般的查詢方法是寫個函式遍歷這個vector,一個個進行比較查詢。
實際上在使用STL的時候,不建議使用迴圈遍歷的查詢方法,建議使用stl的泛型演算法。理由如下:(參考《effictive c++》46條)
效率:泛型演算法通常比迴圈高效。
正確性: 寫迴圈時比呼叫泛型演算法更容易產生錯誤。
可維護性: 與相應的顯式迴圈相比,泛型演算法通常使程式碼更乾淨、更直觀。
1、find模板函式
用stl的find方法查詢一個包含簡單型別的vector中的元素.
程式碼如下:
vector<string> strVec; //加入成員。。 std::find(strVec.begin(),strVec.end(),"aa");
2、find_if模板函式
假如vector的成員是複合型別的物件時,常使用find_if指定具體的查詢方式。複合型別如:
class A
{
public:
A(const std::string str,int id)
{
__str=str;
__id=id;
}
private:
std::string __str;
int __id;
};
函式宣告
template<class InputIterator, class Predicate> InputIterator find_if( InputIterator _First, InputIterator _Last, Predicate_Pred );使用關鍵:最後一個引數是一個一元謂詞
(1)函式
程式碼如下:
bool compare(A& dValue)
{
if(dValue.GetStr().compare(“bb”)==0)
return true;
else
return false;
}
vector<A> a;
A b(“aa”,4);
A c(“bb”,6);
A d(“zz”,7);
a.push_back(b);
a.push_back(c);
a.push_back(d);
vector<A>::iterator t=std::find_if(a.begin(),a.end(),compare);
不過,函式方式在函式內限定了被比較的內容。
(2)函式物件
帶一個引數且返回值限定為bool的函式物件(並重載()操作符號的自定義類)。
程式碼如下:
class findx
{
public:
findx(const string str)
{
__test=str;
}
string GetTest()
{
return __test;
}
bool operator()(A& dValue)
{
if(dValue.GetStr().compare(__test)==0)
return true;
else
return false;
}
private:
string __test;
};
vector<A>::iterator t=std::find_if(a.begin(),a.end(),findx(“33″));
(3)繫結器
STL中的繫結器有類繫結器和函式繫結器兩種,類繫結器有binder1st和binder2nd,而函式繫結器是bind1st和bind2nd,他們的基本目的都是用於構造一個一元的函式物件。
比如這裡我們可以利用bind2nd通過繫結二元函式物件中的第二個引數的方式來實現二元謂詞向一元謂詞的轉換。
程式碼如下:
struct compare: binary_function<A, string,bool>
{
bool operator()( A &val, string str) const
{
if (val.GetStr()== str)
return true;
else
return false;
}
};
vector<A>::iterator t=find_if(a.begin(),a.end(),bind2nd(compare(),”33″));
3、sort模板函式
使用方式也有函式和函式物件方式。
程式碼如下:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool myfunction (int i,int j) { return (i<j); } //函式方式
struct myclass {
bool operator() (int i,int j) { return (i<j);} //函式物件方式
} myobject;
int main () {
int myints[] = {32,71,12,45,26,80,53,33};
vector<int> myvector (myints, myints+8); // 32 71 12 45 26 80 53 33
vector<int>::iterator it;
// using default comparison (operator <):
sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33
// using function as comp
sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)
// using object as comp
sort (myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80)
// print out content:
cout << "myvector contains:";
for (it=myvector.begin(); it!=myvector.end(); ++it)
cout << " " << *it;
cout << endl;
return 0;
}