C++ String Comparison: Why std::strcoll is Tricky and What to Use Instead

2025-09-06

The most frequent problem with std::strcoll is not setting the locale correctly. If you don't call std::setlocale first, the function will default to the "C" locale, which only compares characters based on their numeric value. This can lead to unexpected results, especially with non-ASCII characters.

Common Mistake

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

int main() {
    std::vector<std::string> names = {"éclair", "apple", "banana"};
    std::sort(names.begin(), names.end(), [](const std::string& a, const std::string& b) {
        return std::strcoll(a.c_str(), b.c_str()) < 0; // The locale isn't set!
    });
    for (const auto& name : names) {
        std::cout << name << std::endl;
    }
    return 0;
}

Explanation
In this example, "éclair" might be sorted incorrectly because std::strcoll is using the "C" locale. The "é" character's numeric value is higher than 'a', so "éclair" might be placed after "apple".

Corrected Code

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

int main() {
    // Set the locale to the user's default
    std::setlocale(LC_ALL, ""); 

    std::vector<std::string> names = {"éclair", "apple", "banana"};
    std::sort(names.begin(), names.end(), [](const std::string& a, const std::string& b) {
        return std::strcoll(a.c_str(), b.c_str()) < 0; 
    });
    for (const auto& name : names) {
        std::cout << name << std::endl;
    }
    return 0;
}

Solution
Always remember to call std::setlocale with a valid locale string, like "" to use the system's default, or a specific one like "ja_JP.UTF-8".

For many simple use cases, std::string::compare is a great alternative to std::strcoll. It's generally faster because it performs a simple, byte-by-byte comparison. However, it doesn't handle international characters correctly for sorting purposes.

Example

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

int main() {
    std::vector<std::string> names = {"Zürich", "äpfel", "Apfel"};
    std::sort(names.begin(), names.end()); // This uses std::string::compare
    
    for (const auto& name : names) {
        std::cout << name << std::endl;
    }
    return 0;
}

Result
"Apfel", "Zürich", "äpfel". This is because std::string::compare compares based on character value, and 'A' is numerically less than 'Z', which is less than 'ä'.

When to use std::string::compare
When you don't need locale-sensitive sorting and prioritize performance. This is perfect for sorting lists of file names or other non-linguistic data.

The modern C++ way to handle locale-sensitive comparisons is by using std::locale and std::collate. This approach is more type-safe and object-oriented.

Example

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

int main() {
    // Get the global locale
    const std::locale& loc = std::locale(""); 

    std::vector<std::string> names = {"éclair", "apple", "banana"};

    // Use std::use_facet to get the collate facet
    const std::collate<char>& coll = std::use_facet<std::collate<char>>(loc);

    std::sort(names.begin(), names.end(), [&](const std::string& a, const std::string& b) {
        // The transform member function is often faster for sorting
        return coll.compare(a.c_str(), a.c_str() + a.size(), b.c_str(), b.c_str() + b.size()) < 0;
    });

    for (const auto& name : names) {
        std::cout << name << std::endl;
    }
    return 0;
}

Why this is better
This method is generally considered best practice in modern C++. It's thread-safe and doesn't rely on the global C locale state, making your code more robust. The collate::transform member function can also be used for even greater sorting efficiency if you need to compare the same strings many times.

For serious internationalization work, especially with complex languages, using a dedicated library like ICU is a popular choice. It provides extensive and robust support for collation, case folding, and many other locale-specific operations.

Example (Conceptual)

// This is a conceptual example using the ICU library
#include <unicode/coll.h>
#include <unicode/locid.h>

int main() {
    UErrorCode status = U_ZERO_ERROR;
    Collator* collator = Collator::createInstance(Locale("ja", "JP"), status);
    if (U_FAILURE(status)) {
        // Handle error
    }

    const UnicodeString s1("あいうえお");
    const UnicodeString s2("アイウエオ");

    // Compare two strings using the collator
    if (collator->compare(s1, s2) < 0) {
        // s1 comes before s2
    }

    delete collator;
    return 0;
}

When to use ICU
When you need more advanced features than what the standard library offers, or when you are building an application with a global audience. ICU provides a powerful and portable solution for all your internationalization needs.


cpp



Mastering std::fdim: A Guide to C++ Numerics

When working with std::fdim from the C++ <cmath> library, you're calculating the positive difference between two floating-point numbers


Mastering std::seed_seq::param: Pitfalls and Best Practices

The param function is used within a seed_seq to "reproduce" the internal state of the generator. It's meant to take the current state of the seed_seq and pass it to an output iterator


Common Issues with C++ Regular Expressions

However, I can provide a friendly explanation of the C++ Regular Expressions library and address some common issues that developers encounter when working with it



C++ Containers: Understanding std::unordered_set's swap

The swap method is a member function of the std::unordered_set container. It's used to exchange the contents of two sets efficiently


C++ Concurrency: A Guide to std::osyncstream and Its Destructor

First, let's understand what std::basic_osyncstream is all about. This class, introduced in C++20, is designed to solve a common problem concurrent output to streams


C++ Unordered Maps: Common extract() Pitfalls and Alternatives

The extract method is used to take ownership of a single node (an element) from an unordered_map without having to rehash it


C++ PMR: Troubleshooting unsynchronized_pool_resource

The main issue people face is that the destructor ~unsynchronized_pool_resource doesn't automatically release memory that was allocated by objects that are still "alive


From Theory to Practice: C++ Memory Model and Synchronization Techniques

The C++ memory model is a set of rules that governs how different threads see and interact with memory. In a single-threaded program


A Developer's Guide to C++ basic_ospanstream

Think of std::basic_ospanstream as a special kind of stream, like std::stringstream, but instead of using a dynamically allocated buffer


Embracing Modern C++: Dealing with C++11 Compiler Compatibility Issues

Here's a friendly breakdown of typical C++11 compiler support issues and how to work around them with alternative code examples