jmasterx
jmasterx

Reputation: 54183

Help with the use of std::locale?

I have a class that I want to use to sort my string, bool pair vector. My strings are utf-8 encoded. I want to sort them so that, if the person's locale is set to for example, French, I would hope that if the user typed:

    zap
    apple
    école
    blue
    erable

That it would sort out to be:

apple
blue
école
erable
zap

My std::locale class is this:

class AguiLBLocaleCompare : 
    public std::binary_function<std::pair<std::string, bool>,
    std::pair<std::string,bool>, bool> {
protected:
    const std::collate<char> &coll;
public:
    AguiLBLocaleCompare(std::locale loc)
        : coll(std::use_facet<std::collate<char> >(loc)) {}
    bool operator()(const std::pair<std::string, bool> &a, 
        const std::pair<std::string, bool> &b) const {
        // std::collate::compare() takes C-style string (begin, end)s and
        // returns values like strcmp or strcoll.  Compare to 0 for results
        // expected for a less<>-style comparator.
        return coll.compare(a.first.c_str(), a.first.c_str() + a.first.size(),
            b.first.c_str(), b.first.c_str() + b.first.size()) < 0;
    }
};

and then my item sorting method is:

void AguiListBox::sort()
{
    if(!isReverseSorted())
        std::sort(items.begin(),items.end(),AguiLBLocaleCompare( WHAT_DO_I_PUT_HERE ));
    else
        std::sort(items.rbegin(),items.rend(),AguiLBLocaleCompare(WHAT_DO_I_PUT_HERE));
}

So I'm not sure what to put in the constructor to achieve the desired effect.

I tried std::locale() but it sorted the accents after the z in zap which is not what I want.

items is a

std::vector<std::pair<std::string, bool>>

Thanks

Upvotes: 1

Views: 1396

Answers (1)

ephemient
ephemient

Reputation: 204994

I don't think VC++ supports UTF-8 locales. You should probably convert to wstring and use collate<wchar_t>, or switch to a C++ library that supports UTF-8 locales.

Locale names on Windows/VC++ are different than on UNIXes; see Language and Country/Region Strings (CRT) on MSDN.

Upvotes: 1

Related Questions