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)
...);
精彩评论