在末尾按数字对文件名列表进行排序

Sort a list of file names by number at end

本文关键字:列表 排序 文件名 数字      更新时间:2023-10-16

我有一个文件列表:

foo10.tif
foo2.tif
...
foo102.tif

我想根据文件名末尾的数字对它们进行排序。

最好使用 c++11 和 lambda。

这是有效的。 如果您有任何问题,请告诉我:

#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
   vector<string> aFiles =
   {
      "foo10.tif",
      "foo2.tif",
      "foo102.tif",
   };
   sort(begin(aFiles), end(aFiles), [](const string& a, const string& b)
   {
      auto RemoveExtension = [](const string& s) -> string
      {
         string::size_type pos = s.find_last_of('.');
         if (pos != string::npos)
            return s.substr(0, pos);
         return s;
      };
      string partA = RemoveExtension(a), partB = RemoveExtension(b);
      if (partA.length() != partB.length())
         return partA.length() < partB.length();
      return partA < partB;
   } );
   for (string s : aFiles)
      cout << s << endl;
}