Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

13.5. Sorting Localized Strings

Problem

You have a sequence of strings that contain non-ASCII characters, and you need to sort according to local convention.

Solution

The locale class has built-in support for comparing characters in a given locale by overriding operator. You can use an instance of the locale class as your comparison functor when you call any standard function that takes a functor for comparison. (See Example 13-8.)

Example 13-8. Locale-specific sorting

#include <iostream>
#include <locale>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

bool localeLessThan (const string& s1, const string& s2) {

   const collate<char>& col =
     use_facet<collate<char> >(locale()); // Use the global locale

   const char* pb1 = s1.data();
   const char* pb2 = s2.data();

   return (col.compare(pb1, pb1 + s1.size(),
                       pb2, pb2 + s2.size()) < 0);
}

int main() {

   // Create two strings, one with a German character
   string s1 = "diät";
   string s2 = "dich";

   vector<string> v;
   v.push_back(s1);
   v.push_back(s2);

   // Sort without giving a locale, which will sort according to the
   // current global locale's rules.
   sort(v.begin(), v.end());
   for (vector<string>::const_iterator p = v.begin();
        p != v.end(); ++p)
      cout << *p << endl;

   // Set the global locale to German, and then sort
   locale::global(locale("german"));
   sort(v.begin(), v.end(), localeLessThan);
   for (vector<string>::const_iterator p = v.begin();
        p != v.end(); ++p)
      cout << *p << endl;
}

The first sort follows ASCII sorting convention, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page