2011-10-10 34 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) 
    ...); 
相關問題