我错误地使用了以下代码片段,使用boost-filesystem和boost-regexp从作为参数输入的目录中获取绝对path+filenames。
其中input_dir是保存来自命令行的参数的变量,该参数表示要遍历的目录的名称,
string dir_abs_name = "./" + input_dir;
string file_abs_name;
path current_dir(dir_abs_name);
boost::regex pattern("m.*"); // list all files starting with m
for (directory_iterator iter(current_dir),end; iter!=end; ++iter) {
string name = iter->path().leaf();
if (regex_match(name, pattern)) {
file_abs_name = dir_abs_name + name;
input_file = str_to_char(file_abs_name); // my own function that converts string to char* (needed that for another method later on in the code)
std::cout << "--> considering file " << input_file << "... \n";
}
}现在我遇到了一个问题,列表不是按字母顺序排列的。我得到的是随机匹配,而不是任何特定的顺序。有没有办法强制按字母顺序排列?
谢谢。
编辑:值得一提的是,在程序中,我有时只处理目录中整个文件列表的一个子集。当我传递一个参数进行选择时,我会这样做,假设目录中1000个文件中只有4个文件。可以在检索列表后对它们进行排序。但检索仍然是随机的。
发布于 2011-07-13 22:34:52
为什么不在(std:: vector )中缓存结果,对向量进行排序,然后迭代排序后的向量来执行处理呢?
例如:
string dir_abs_name = "./" + input_dir;
string file_abs_name;
path current_dir(dir_abs_name);
boost::regex pattern("m.*"); // list all files starting with m
std::vector<std::string> accumulator;
for (directory_iterator iter(current_dir),end; iter!=end; ++iter) {
string name = iter->path().leaf();
if (regex_match(name, pattern)) {
file_abs_name = dir_abs_name + name;
accumulator.push_back(file_abs_name);
}
}
std::sort(accumulator.begin(), accumulator.end());
std::vector<std::string>::iterator iter;
for (iter = accumulator.begin(); iter != accumulator.end(); ++iter) {
char* input_file = str_to_char(*iter); // my own function that converts string to char* (needed that for another method later on in the code)
std::cout << "--> considering file " << input_file << "... \n";
}https://stackoverflow.com/questions/6680446
复制相似问题