【发布时间】:2013-07-30 12:57:17
【问题描述】:
我正在使用 boost 的文件系统和 std::max_element() 在给定目录中查找名称最长的文件:
#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、mouse.dat、elephant.dat 的目录 Animals,输出为:
Longest file name: Animals/mouse.dat has 17 characters
这既不是最长也不是最短的文件名。上面的代码有什么问题?
【问题讨论】: