A word-frequency std::map<std::string, int> is searched with std::string_view tokens; why does find(token) not compile, and how do you fix it without allocating?
answer
- the default comparator's parameter type
- explicit conversion from string_view
- is_transparent
- std::less<> since C++14
- which members accept K, by standard
basics
~20 sWith std::lessstd::string, find takes const std::string&, and std::string_view does not convert to it implicitly. Declare the map with a transparent comparator such as std::less<>, and the C++14 find, count and lower_bound templates compare the string_view directly.
solid answer
~40 sThe default comparator `std::less<std::string>` only compares two `std::string`s, so `find` accepts `const key_type&`. Constructing a `std::string` from a `std::string_view` is explicit, so `freq.find(token)` fails to compile; `freq.find(std::string(token))` compiles but allocates for every long token. Since C++14 the lookup members also have templates taking any `K`, which participate only when `Compare::is_transparent` names a type. `std::less<>` (that is, `std::less<void>`) declares it, and its `operator()` compares `std::string` with `std::string_view` through their mixed `operator<`. So `std::map<std::string, int, std::less<>>` gives allocation-free `find`, `count`, `lower_bound`, `upper_bound`, `equal_range` and C++20 `contains`. C++23 adds heterogeneous `erase` and `extract`; C++26 adds `operator[]`, `at`, `try_emplace` and `insert_or_assign`. libc++'s status pages at LLVM 23.1.4 list neither of those two papers as implemented.
code
cpp · 19 lines#include <functional>
#include <iostream>
#include <map>
#include <string>
#include <string_view>
int main() {
// word-frequency index; std::less<> is transparent (it has is_transparent)
std::map<std::string, int, std::less<>> freq{{"order", 3}, {"price", 7}};
std::string_view line = "price level";
std::string_view word = line.substr(0, 5); // "price", no allocation
if (auto it = freq.find(word); it != freq.end()) // compares string with string_view
++it->second;
std::cout << "price=" << freq.find(word)->second
<< " contains(\"order\")=" << freq.contains("order") // C++20
<< " count(\"bid\")=" << freq.count("bid") << '\n';
}go deeper
Know that a std::map with the default comparator looks up by the exact key type, and that a std::string_view does not silently become a std::string.
Explain is_transparent and std::less<>, and which lookup members gained template overloads in C++14 and C++20.
Fix allocation-heavy lookups with a transparent comparator, avoid comparators that build temporaries per comparison, and check library support for the C++23 and C++26 overloads.
Decide whether string-keyed maps in shared code default to std::less<>, weighing allocation savings against overload-set changes and uneven toolchain support.
## Why the call fails A **word-frequency index** that counts tokens from a log line is a natural `std::map<std::string, int>`. The tokenizer produces `std::string_view` slices of the line, so no token is copied. Then: ```cpp std::map<std::string, int> freq; std::string_view w = "price"; freq.find(w); // error: no matching member function for call to 'find' ``` That is Apple clang 21's diagnostic. The default comparator is `std::less<std::string>`, whose `operator()` takes two `const std::string&`, so the non-template `find(const key_type&)` is the only candidate. `std::string` can be constructed from a `string_view`, but that constructor is **explicit**, so no implicit conversion happens. Writing `freq.find(std::string(w))` compiles but builds a temporary string, which allocates once the token is longer than the implementation's small-string buffer, on every lookup. ## Transparent comparators C++14 added member function **templates** to the ordered associative containers: `find`, `count`, `lower_bound`, `upper_bound` and `equal_range` gained overloads taking `const K&` for any type `K`. To avoid changing the meaning of existing code, those templates **do not participate in overload resolution** unless `Compare::is_transparent` is valid and denotes a type. A comparator opts in by declaring it: - **`std::less<>`**: the primary template is declared `template<class T = void> struct less;`, so `std::less<>` is the `std::less<void>` specialization. The standard declares its call operator as a template, `template<class T, class U> constexpr auto operator()(T&& t, U&& u) const`, returning `std::forward<T>(t) < std::forward<U>(u)`, and gives it `using is_transparent = /* unspecified */;`. With `std::string` and `std::string_view`, that calls their mixed comparison operators, so nothing is converted. `std::greater<>` is transparent in the same way, for maps ordered high to low. - A **custom comparator** declares `using is_transparent = void;` and provides `operator()` overloads for each argument-type pair it supports. The fix for the index is one template argument: `std::map<std::string, int, std::less<>>`. `freq.find(w)` now compares `w` against stored keys directly, and `freq.contains("order")` compares against a `const char*` without building a string. ## Which members accept another key type, by standard | Standard | Members with a heterogeneous overload on `std::map` and `std::set` | |---|---| | C++14 | `find`, `count`, `lower_bound`, `upper_bound`, `equal_range` | | C++20 | `contains` | | C++23 | `erase`, `extract` | | C++26 | `operator[]`, `at`, `try_emplace`, `insert_or_assign` on `std::map`; `insert` on `std::set` | Support lags the standard here. libstdc++ in GCC 16 guards both the C++23 erase overloads and the C++26 insertion overloads in its map header. libc++'s status pages at LLVM 23.1.4 list the C++23 paper (heterogeneous erasure) and the C++26 paper (the remaining heterogeneous overloads) with no completed release, and Apple clang 21 rejected `freq.erase(w)` under `-std=c++23` and `freq[w]` under `-std=c++2c`. So `++freq[w]` still needs `++freq[std::string(w)]` or a `find` plus `try_emplace` on most toolchains today. The feature-test macros `__cpp_lib_associative_heterogeneous_erasure` and `__cpp_lib_associative_heterogeneous_insertion` say what the library you build against provides. ## Pitfalls - **Consistency across types.** A transparent comparator must order a `K` against keys exactly as it orders keys among themselves; for `std::string` and `std::string_view` that holds, because both compare character sequences the same way. - **Hidden temporaries.** A custom transparent comparator whose only `operator()` takes `(const std::string&, const std::string&)` still compiles for `const char*` arguments, but now builds a `std::string` on *every comparison* in the tree walk, which is worse than one conversion up front. - **Changed overload sets.** Making a comparator transparent changes which `find` is chosen for every call site, including ones passing types that convert implicitly; check that none relied on the old conversion. - **Pointer keys.** `std::less<>` on `const char*` keys compares addresses, not characters; use `std::string` or `std::string_view` keys for text. ## The index in practice 1. Declare `std::map<std::string, int, std::less<>>`. 2. Look tokens up with `find(w)`; on a hit, increment through the iterator. 3. On a miss, insert with `try_emplace(std::string(w), 1)`, paying for the string only when a new word is stored. 4. Keep the keys owning (`std::string`): a map keyed by `std::string_view` would dangle once the log line buffer is reused. 5. Give companion containers the same comparator: a stop-word filter declared as `std::set<std::string, std::less<>>` lets `stop_words.contains(w)` skip the conversion too, so the whole hot loop runs without building a single `std::string` for words already seen. The gain is easiest to confirm with an allocation counter or a heap profiler on a realistic log sample: the transparent version should show allocations only for new words, while the converting version allocates for every long token on every line.
- Why did the committee gate the heterogeneous overloads on is_transparent instead of enabling them for every comparator?Enabling them unconditionally would change behaviour of existing code. With `std::less<std::string>`, a `find("abc")` call converts once to `std::string`; a template `find(const K&)` would instead pass `const char*` into a comparator that converts on every comparison, or fail to compile. Opting in through `is_transparent` lets the comparator author declare that it really compares mixed types consistently.
- How do you get heterogeneous lookup on a std::map with a custom comparator for case-insensitive keys?Give the comparator `using is_transparent = void;` and `operator()` overloads for `(std::string_view, std::string_view)`, which covers `std::string` and literals through implicit conversion to `std::string_view`. Every overload must apply the same case-folding rule, or lookups with a view and with a string will disagree about equivalence.
- std::string_view converts implicitly to std::string, so find(token) just works
- Any comparator enables the find(const K&) template automatically
- Switching to std::less<> also makes freq[token] compile on every compiler
- Keying the map by std::string_view is the simplest way to avoid allocations
- Heterogeneous lookup has existed since C++98
Assumes C++23: heterogeneous find since C++14, contains since C++20, heterogeneous erase and extract since C++23; operator[], at and try_emplace overloads follow in C++26.