【问题标题】:How to perform the Microsoft filename sorting in C/C++?如何在 C/C++ 中执行 Microsoft 文件名排序?
【发布时间】:2014-01-27 18:44:55
【问题描述】:

我已经成功使用了C#中所谓的“Windows排序”,如下图所示。

public class NativeMethods
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode, EntryPoint = "StrCmpLogicalW")]
    public static extern int StrCmpLogical(string x, string y);
}

private class NaturalSortComparer : IComparer
{
    public int Compare(object a, object b)
    {
        return NativeMethods.StrCmpLogical((string)a, (string)b);
    }
}

来自 Unix 方面,我对 Microsoft 风格和 C++ 变体知之甚少,所以请耐心等待。

如何使用上述方法在 C++ 中对某些文件进行排序?以防万一:我没有在这个特定项目中使用 MFC。

我的文件在 C++ std::list 中,我需要按如下(或类似)对它们进行排序:

myFiles.sort();

【问题讨论】:

  • 您为什么要为此进行 PInvoke? Directory.EnumerateFiles 应该为你做这件事。
  • 只要写一个基于StrCmpLogical的比较谓词,传递给sort
  • “你为什么要为此做 PInvoke?”我需要以10. 开头的文件名放在9. 之后你建议的方法可以吗?
  • 我想如果您搜索“自然排序”一词,您会找到一些答案。例如,see this question

标签: c# c++ windows


【解决方案1】:

自尊:

解决办法如下:

list<string> myFiles;
myFiles.push_back("10.somefilename.ext");
myFiles.push_back("9.somefilename.ext");
myFiles.sort(compare);

另外:

bool compare(const string& first, const string& second)
{
    wstring lhs = widen(first);
    wstring rhs = widen(second);
    bool ordered = StrCmpLogicalW(lhs.c_str(), rhs.c_str()) < 0;
    return ordered;
}

最后:

wstring widen(string text)
{
    locale loc("");
    vector<wchar_t> buffer(text.size());
    use_facet< std::ctype<wchar_t> > (loc).widen(text.data(), text.data() + text.size(), &buffer[0]);
    return wstring(&buffer[0], buffer.size());
}

你的自我。

【讨论】:

  • 您能否在排序前遍历myFiles 列表,然后遍历widen 每个字符串,生成一个可以排序的list&lt;wstring&gt;?如果您有任何类型的大列表(当前算法可能会反复加宽),它可能比比较期间的加宽速度要快得多。
猜你喜欢
  • 2017-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-11
  • 2021-05-08
  • 2020-07-30
  • 2021-11-06
  • 1970-01-01
相关资源
最近更新 更多