开发者

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/?

开发者 https://www.devze.com 2023-04-12 05:26 出处:网络
So we have a set of file names\\urls like file, folder/file, folder/file2, folder/file3, folder/folder2/fileN, etc. We are given a string like folder/. We want to find folder/file, folder/file2,folder

So we have a set of file names\urls like file, folder/file, folder/file2, folder/file3, folder/folder2/fileN, etc. We are given a string like folder/. We want to find folder/file, folder/file2, folder/file3, and most intrestingly folder/folder2/ (we do not want to list forlder2 content开发者_C百科s just show that it exists and it can be searched). Is such thing possible via STL and Boost, and how to do it?

Ups - just found out that I already loocked for this once a while ago here... but havent found correct answer yet...


A relatively simply C++11 implementation. This could be modified to C++03 easily. (caveat: have not compiled or tested this).

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
});


This sounds like a great opportunity to use regex stuff in Boost/C++11

Something like

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
});

Sorry I can't provide the regex syntax... I need to study that more.


The ordered containers have a set of methods that are quite useful in finding a range of iterators: lower_bound and upper_bound. In your case, you want to use:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号