我使用升壓轉換器的文件系統和std :: max_element()來查找最長名的文件在指定目錄:Max_element與升壓directory_iterator
#include <iostream>
#include <iterator>
#include <algorithm>
#include <string>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
bool size_comp(directory_entry de1, directory_entry de2 )
{
return de1.path().string().size() < de2.path().string().size();
}
int main(int argc, char* argv[])
{
path p (argv[1]); // p is a path to a directory
directory_iterator itr (p);
directory_iterator itr_end;
directory_iterator itr_max=::max_element(itr,itr_end,size_comp);
int max_size = itr_max->path().string().size();
cout << "Longest file name: " << itr_max->path() << " has "
<< max_size << " characters" << endl;
return 0;
}
對於目錄中的動物與文件cat.dat,鼠標.DAT,elephant.dat輸出爲:
Longest file name: Animals/mouse.dat has 17 characters
這既不是最長的,也不是最短的文件名。上面的代碼有什麼問題?