Skip to content
C++ Basics: Look Up String Keys with a String View

C++ Basics: Look Up String Keys with a String View

November 3, 2026

Enable heterogeneous ordered-map lookup with a transparent comparator.

Prepare a scratch directory

Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and its standard-library headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.

Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save this as map-transparent-string-view-demo.cpp:

#include <functional>
#include <iostream>
#include <map>
#include <string>
#include <string_view>

int main() {
    const std::map<std::string, int, std::less<>> ports{
        {"http", 80}, {"https", 443}
    };
    const std::string_view requested = "https";
    const auto found = ports.find(requested);
    if (found != ports.end()) {
        std::cout << requested << ": " << found->second << '\n';
    }
    const std::string_view missing = "ssh";
    std::cout << std::boolalpha
              << "SSH present: " << (ports.find(missing) != ports.end()) << '\n';
}

Compile and run it. The second command runs only after compilation succeeds:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic map-transparent-string-view-demo.cpp -o map-transparent-string-view-demo &&
./map-transparent-string-view-demo

Observed output:

https: 443
SSH present: false

Read the result

The map owns string keys while lookup accepts string_view directly. The transparent comparator enables this overload without constructing a temporary string key.

Apply it carefully

Keep the view backing storage valid during lookup. The comparator must order every supported key combination consistently. This example uses std::less<> and compatible string types; transparency alone cannot make an arbitrary comparison correct.

The C++ working draft documents the relevant container rules. This example uses only features available in C++20, even though the linked draft also includes newer additions.

Clean up

Remove only the source and executable created here, then remove the empty practice directory:

rm -- map-transparent-string-view-demo.cpp map-transparent-string-view-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect its remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on