2011-09-19 35 views
2
boost::filesystem::recursive_directory_iterator end, begin(directory); 

auto num_of_files=std::count_if(begin, end, 
     std::not1(boost::filesystem::is_directory))); 

我想否定上述目錄迭代器的is_directory函數,但是碰到了一堵磚牆。我已經嘗試將not1指定爲bool(*)(const boost::filesystem::path&)的模板,並嘗試靜態轉換該函數,但都未成功。在std算法中反向提升is_directory

我知道我可以求助於一個lamdba,但是如果它工作的話這個更清潔。

由於

+0

你收到了什麼錯誤? –

回答

6

std::not1需要一個函數對象作爲其參數。這個函數對象可以用std::ptr_fun得到,所以這應該工作:

auto num_of_files=std::count_if(begin, end, 
     std::not1(std::ptr_fun((bool(*)(const boost::filesystem::path&))boost::filesystem::is_directory))); 

(括號的數量,可能是不正確的)。順便說一句,你需要演員,因爲is_directory是一個重載功能。

不過,既然你標記你的問題C++ 11,你可以使用lambda表達式:

auto num_of_files=std::count_if(begin, end, [](const boost::filesystem::path& p) { return !boost::filesystem::is_directory(p); }); 
+0

啊,我晚了約30秒:) –

+0

工作過的魅力我更喜歡這種語法,它對我來說更好:std :: ptr_fun (boost :: filesystem :: is_directory)... – 111111

+0

@ 111111,你是瘋了,或者可能是機器人。我的意思是說,儘可能善意。 –

0

NOT1接受函數子類的實例,這應該是一個Adaptable Predicate(即返回值的類型定義等。 ),而你試圖用一個函數指針來提供它。所以你需要把它包裝在仿函數中,ptr_fun可能會有所幫助。 也許這會工作(假設使用命名空間std;使用空間boost):

auto num_of_files=count_if(begin, end, not1(ptr_fun(filesystem::is_directory))); 
0

你需要ptr_fun,

這種相當精細的插圖應打印1三次:(另見http://ideone.com/C5HTR

#include <functional> 
#include <string> 
#include <algorithm> 
#include <iostream> 

bool pred(const std::string& s) 
{ 
    return s.size() % 2; 
} 

int main() 
{ 
    std::string data[] = { "hello", "world!" }; 

    std::cout << std::count_if(data, data+2, 
      pred) << std::endl; 

    std::cout << std::count_if(data, data+2, 
      std::ptr_fun(pred)) << std::endl; 

    std::cout << std::count_if(data, data+2, 
      std::not1(std::ptr_fun(pred))) << std::endl; 

    return 0; 
}