Sort files with boost file system

here is my problem: I have a stack of files with names like "_X1.bla.txt", "_X101.bla.txt", _X47.bla.txt "that I read with the boost :: file system added to std :: vector .

As you can see from the example, names do not start with numbers. In this example, the result will be 1, 47, 101. If you tell me how I can extract numbers from files, I have to auto-sort the files myself.

Best hu dao

+4
source share
3 answers

You can use boost::regex to extract a number as a string, convert the string to a number in a custom comparator for std::sort , to sort the std::vector your files

 boost::regex re("(\\d+)"); boost::match_results<std::string::const_iterator> what1,what2; template <typename T> T st2num ( const std::string &Text ) { std::stringstream ss(Text); T result; return ss >> result ? result : 0; } struct mysort { bool operator ()(const std::string & a,const std::string & b) { boost::regex_search(a.cbegin(), a.cend(), what1, re, boost::match_default); boost::regex_search(b.cbegin(), b.cend(), what2, re, boost::match_default); return st2num<int>(what1[1]) < st2num<int>(what2[1]); } }; 

And then,

//std::vector<std::string> vec{"_X1.bla.txt", "_X101.bla.txt", "_X47.bla.txt"}; std::sort( vec.begin() , vec.end() ,mysort() );

+3
source

If you have all the names in the container (something like std :: vector filenames), you can do

 std::sort(filenames.begin(),filenames.end()) 

and he will use the default sort function. If you want to make customs you can do:

 struct sort_functor { bool operator ()(const std::string & a,const std::string & b) { return a < b;// or some custom code } }; void test() { std::vector<std::string> filenames; std::sort(filenames.begin(),filenames.end(),sort_functor()); } 
+2
source

Suppose you used boost_ystemator. Using an iterator, you have access to the file name as a string.

Use regex (\ d +) to extract a number (if multiple)

and instead of using the "pair vector (int, string)" you can directly use an ordered map.

0
source

Source: https://habr.com/ru/post/1501515/


All Articles