Home > Backend Development > C++ > How can I customize the comparator for a map in C to sort keys by their length?

How can I customize the comparator for a map in C to sort keys by their length?

Susan Sarandon
Release: 2024-11-04 08:02:02
Original
566 people have browsed it

How can I customize the comparator for a map in C   to sort keys by their length?

Customizing Comparators for Maps

In C , std::map uses a comparator to order its elements. By default, maps use the less-than operator (<) to compare keys. However, it is possible to override this default behavior by providing a custom comparator.

This question discusses how to customize the comparator for a map to sort keys by their length rather than alphabetically. Here's the solution:

Solution using a Custom Class

std::map allows for up to four template type arguments, the third one being a comparator. Here's an example of a custom class that implements a comparator based on string length:

<code class="cpp">struct cmpByStringLength {
    bool operator()(const std::string& a, const std::string& b) const {
        return a.length() < b.length();
    }
};
Copy after login

To use this custom comparator, create a map with the following template arguments:

<code class="cpp">std::map<std::string, std::string, cmpByStringLength> myMap;</p>
<p><strong>Solution using Constructor Argument</strong></p>
<p>Alternatively, you can pass a comparator to the map's constructor. This syntax is equivalent to the previous example:</p>
<pre class="brush:php;toolbar:false"><code class="cpp">std::map<std::string, std::string, cmpByStringLength> myMap(cmpByStringLength());</code>
Copy after login

Note: When comparing by length, only one string of each length can be present in the map as a key.

The above is the detailed content of How can I customize the comparator for a map in C to sort keys by their length?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template