在c++中使用StrCmpLogicalW函数进行自然排序

Natural sort order in C++ using StrCmpLogicalW function in this library shlwapi.dll

本文关键字:自然 排序 函数 StrCmpLogicalW c++      更新时间:2023-10-16

我尝试学习如何使用StrCmpLogicalW函数。c#中有一篇关于c#自然排序顺序的文章。但我正在寻找c++语法。

谢谢。

你是说你想使用该函数对字符串集合进行排序吗?

bool mycomp(PCWSTR lhs, PCWSTR rhs)
{
    return StrCmpLogicalW(lhs,rhs) < 0;
}

或者如果你使用std::wstring:

bool mycomp(const std::wstring & lhs, const std::wstring & rhs)
{
    return StrCmpLogicalW(lhs.c_str(),rhs.c_str()) < 0;
}

然后你可以用这个函数调用std::sort,假设你有一个std::vector<std::wstring>叫做v:

std::sort(v.begin(), v.end(), mycomp);

我终于弄明白了。这是函数。如果您自己有头文件,那么务必将shlwapi.h和vcclr.h头文件放在任何头文件之前。这是我一直在努力解决的问题。我不完全明白为什么会这样。如果谁有好的解释,欢迎发表评论。此外,如果有人知道如何将最后三行代码组合成单个返回语句,欢迎添加注释。

#include "shlwapi.h"  //needed this for StrCmpLogicalW
#include <vcclr.h>   //needed this for PtrtoStringChars
//your own header files
ref class FileInfoNameComparer: public IComparer
    {
    private:
       virtual int Compare( Object^ x, Object^ y ) sealed = IComparer::Compare
       {
            FileInfo^ objX = gcnew FileInfo(x->ToString());
            FileInfo^ objY = gcnew FileInfo(y->ToString());
            pin_ptr<const wchar_t> wch1 = PtrToStringChars(objX->Name);
            pin_ptr<const wchar_t> wch2 = PtrToStringChars(objY->Name);
            return  StrCmpLogicalW(wch1, wch2);
       }
    };

要使用StrCmpLogicalW,您可能还需要采取步骤在链接中包含相应的库。对我来说有效的一种方法是使用下面的#pragma和#include:

#pragma comment(lib, "Shlwapi.lib")
#include <shlwapi.h> //for StrCmpLogicalW