首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用模式regexp匹配的排序目录列表

使用模式regexp匹配的排序目录列表
EN

Stack Overflow用户
提问于 2011-07-13 22:23:06
回答 1查看 3.2K关注 0票数 1

我错误地使用了以下代码片段,使用boost-filesystem和boost-regexp从作为参数输入的目录中获取绝对path+filenames。

其中input_dir是保存来自命令行的参数的变量,该参数表示要遍历的目录的名称,

代码语言:javascript
复制
  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个文件。可以在检索列表后对它们进行排序。但检索仍然是随机的。

EN

回答 1

Stack Overflow用户

发布于 2011-07-13 22:34:52

为什么不在(std:: vector )中缓存结果,对向量进行排序,然后迭代排序后的向量来执行处理呢?

例如:

代码语言:javascript
复制
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"; 
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6680446

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档