I need to sort a C++ std::vector<std::string> fileNames. The fileNames are labeled as such
YYDDDTTTT_Z_SITE
YY = Year (i.e 2009 = 09, 2010 = 10) DDD = Day of the year (i.e 1 January = 001, 31 December = 365) TTTT = Time of the day (i.e midnight = 0000, noon = 1200)
ZONE = Will be either E or W
SITE = Four letter site name (i.e HILL, SAMM)
I need the strings to be sorted by the following order: ZONE, SITE, YY, DDD, TTTT
Use std::sort with a comparison function.
(The link has a nice example)
The easy part: write the sort itself:
// Return true if the first arg is strictly less than the second
bool compareFilenames(const std::string& rhs, const std::string& lhs);
...
std::sort(fileNames.begin(), fileNames.end(), &compareFilenames);
The harder part: writing the comparison itself. In pseudocode, for full generality:
bool compareFilenames(const std::string& lhs, const std::string& rhs)
{
parse the filenames
if (lhs zone != rhs zone)
return lhs zone < rhs zone
if (lhs site != rhs site)
return lhs site < rhs site
...
return false
}
where lhs site, etc. are the individual bits of data you need to sort by, picked out of the filename.
Given the strict file naming structure you have, though, and your specific sorting needs, you can actually get away with just splitting the string by the first '_' character and doing a lexicographical compare of the second chunk, followed the first chunk if the second chunk is equal. That will make the code to parse the filename much easier, at the potential cost of flexibility if the file naming format ever changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With