2011-10-10 39 views
1

因此,我们有一组文件名\ url,如file, folder/file, folder/file2, folder/file3, folder/folder2/fileN等。我们给出了一个字符串,如folder/。我们想要找到folder/filefolder/file2,folder/file3,并且最有趣的是folder/folder2/(我们不想列出forlder2的内容,只是表明它存在并且可以被搜索到)。通过STL和Boost可以实现这种功能吗?以及如何做到这一点?有一个只有文件名(a,f/a,f/b,f/f/c等)的std :: set如何通过给定的f /来列出目录?

UPS - 刚刚发现我已经loocked对于这个曾经在不久前here ......但还没有找到正确的答案了......

+0

尝试'substr()'。一个合适的数据结构可能是一个*前缀树*(或“trie”),但是对于少数不应该是必需的元素。 –

+0

为什么你在std :: set中使用它?根据您的要求定制自定义类。 – balki

+1

[set 可能重复:如何列出不以给定字符串开头并以'/'?]结尾的字符串(http://stackoverflow.com/questions/7169320/setstring-how-to-list-not-strings-开始与 - 给串和结束的,有) – Rella

回答

1

这听起来像一个伟大的机会,以加速使用正则表达式的东西/ 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 
}); 

对不起,我不能提供正则表达式的语法...我需要学习更多。

1

一个相对简单的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 
}); 
1

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

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