c++11呼叫成員函式mem_fn和適合普通函式指標
阿新 • • 發佈:2019-02-20
在C++11之前,呼叫一個成員函式指標做為容器的回撥演算法時,可以根據其容器記憶體儲的內容是物件還是指標呼叫相關的mem_fun和_mem_fun_ref函式來與演算法等進行適配,搭配使用。
在c++11中加入mem_fn來對成員函式的呼叫進行相關的封裝,不過也需要對方法指標定義為成員函式的形式。
例項程式碼如下所示:
執行效果如下圖#include <functional> #include <algorithm> #include <string> #include <vector> #include <iostream> using namespace std; void findEmptyString(const vector<string>& strings) { auto end = strings.end(); auto it = find_if(strings.begin(), end, mem_fn(&string::empty) ); //此處的成員函式指標要表示為相應的成員函式的形式,且使用mem_fn進行包裝 if ( it == end) { cout<<"no empty strings~"<<endl; }else { cout<<"empty string at position: "<<it - strings.begin()<<endl; } } int main() { vector<string> myVector; string one = "buaa"; string two = ""; myVector.push_back(one); myVector.push_back(one); myVector.push_back(two); myVector.push_back(one); findEmptyString(myVector); system("pause"); return 0; }
當然,這裡最好的,最為優雅的方式還是轉用lambda的方式進行實現。如下程式碼所示:
auto it = find_if(strings.begin(), end,
[](const string* str){ return str->empty(); });
實現相同的功能,愛死你了auto。。