【问题标题】:Having a std::set with only file names (a, f/a, f/b, f/f/c, etc) how to list a directory by given f/?拥有一个只有文件名(a、f/a、f/b、f/f/c 等)的 std::set 如何通过给定的 f/ 列出目录?
【发布时间】:2011-12-04 18:07:16
【问题描述】:

所以我们有一组文件名\url,如file, folder/file, folder/file2, folder/file3, folder/folder2/fileN 等。我们得到一个字符串,如folder/。我们想找到folder/filefolder/file2folder/file3,最有趣的是folder/folder2/(我们不想列出forlder2的内容,只是表明它存在并且可以搜索)。是否可以通过 STL 和 Boost 实现这样的事情,以及如何做到这一点?

Ups - 刚刚发现我已经在不久前寻找过这个here...但还没有找到正确的答案...

【问题讨论】:

标签: c++ search boost stl set


【解决方案1】:

这听起来像是在 Boost/C++11 中使用正则表达式的好机会

类似

std::set<std::string> theSet;
// Get stuff into theSet somehow

const std::string searchFor= "folder/";

std::set<std::string> matchingSet;
std::for_each(std::begin(theSet), std::end(theSet),
              [&matchingSet, &searchFor] (const std::string & s)
{
    if (/* the appropriate code to do regex matching... */)
        matchingSet.insert(s); // or the match that was found instead of s
});

抱歉,我无法提供正则表达式语法...我需要进一步研究。

【讨论】:

    【解决方案2】:

    一个相对简单的 C++11 实现。这可以很容易地修改为 C++03。 (警告:尚未编译或测试过)。

    std::set<std::string> urls;           // The set of values you have
    std::string key_search = "folder/";   // text to search for
    
    std::for_each(
        urls.begin(),
        urls.end(),
        [&key_search] (const std::string& value)
    {
        // use std::string::find, this will only display
        // strings that match from the beginning of the 
        // stored value:
        if(0 == value.find(key_search))
            std::cout << value << "\n"; // display
    });
    

    【讨论】:

      【解决方案3】:

      有序容器有一组在查找迭代器范围时非常有用的方法:lower_boundupper_bound。在你的情况下,你想使用:

      std::for_each(
          path_set.lower_bound("folder/"),
          path_set.upper_bound("folder0"), // "folder" + ('/'+1)
          ...);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-19
        • 1970-01-01
        • 2012-06-26
        • 1970-01-01
        • 1970-01-01
        • 2014-09-07
        相关资源
        最近更新 更多