Natural sort order in C++ using StrCmpLogicalW function in this library shlwapi.dll
I try to learn how to use the StrCmpLogicalW function. There is a post in C# Natural Sort Order in C#. But I am looking for syntax in C++.
开发者_C百科Thank you.
Are you saying you want to sort an collection of strings using that function?
bool mycomp(PCWSTR lhs, PCWSTR rhs)
{
return StrCmpLogicalW(lhs,rhs) < 0;
}
Or if you're using std::wstring
:
bool mycomp(const std::wstring & lhs, const std::wstring & rhs)
{
return StrCmpLogicalW(lhs.c_str(),rhs.c_str()) < 0;
}
Then you can call std::sort using that function, let's say you have an std::vector<std::wstring>
called v:
std::sort(v.begin(), v.end(), mycomp);
I finally got it figured out. Here is the function. It is critical that you put the shlwapi.h and vcclr.h header files before any of your own header files if you have any. That was the issue I have been struggled with. Don't fully understand why it is. If anyone have an good explanation, welcome to make comment. Also, if anyone know how to combine the last three line of code to a single return statement, welcome to add comment.
#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);
}
};
To use StrCmpLogicalW you may also need to take steps to include the corresponding library in your linking. One way that worked for me is to use the following #pragma along with the #include:
#pragma comment(lib, "Shlwapi.lib")
#include <shlwapi.h> //for StrCmpLogicalW
精彩评论