Working with String Views

string_view in unordered_map

Can std::string_view be used as a key in std::unordered_map?

Abstract art representing computer programming

Yes, std::string_view can be used as a key in std::unordered_map, but it requires a custom hash function and comparison function.

std::string_view does not own the data, so you need to ensure the underlying data remains valid for the map's lifetime.

Custom Hash and Comparison Functions

To use std::string_view as a key, you need to define custom hash and comparison functions:

#include <iostream>
#include <string_view>
#include <unordered_map>

struct StringViewHash {
  std::size_t operator()(
    std::string_view str
  ) const noexcept {
    return std::hash<std::string_view>{}(str);
  }
};

struct StringViewEqual {
  bool operator()(
    std::string_view lhs,
    std::string_view rhs
  ) const noexcept {
    return lhs == rhs;
  }
};

int main() {
  std::unordered_map<
    std::string_view, int,
    StringViewHash, StringViewEqual
  > map;

  std::string key{"example"};
  map[key] = 42;

  std::cout << "Value: " << map["example"];
}
Value: 42

Ensuring Validity

The underlying string data must remain valid for the entire lifetime of the std::unordered_map entry. Be cautious with temporary strings:

#include <iostream>
#include <string_view>
#include <unordered_map>

struct StringViewHash {
  std::size_t operator()(
    std::string_view str
  ) const noexcept {
    return std::hash<std::string_view>{}(str);
  }
};

struct StringViewEqual {
  bool operator()(
    std::string_view lhs,
    std::string_view rhs
  ) const noexcept {
    return lhs == rhs;
  }
};

int main() {
  std::unordered_map<
    std::string_view,
    int, StringViewHash,
    StringViewEqual
  > map;

  {
    std::string key{"example"};
    map[key] = 42;  // Key is valid here
  }                 // Key is destroyed here

  // Accessing the map with the destroyed key
  std::cout << "Value: " << map["example"]; 
}
undefined behavior or runtime error

Conclusion

Using std::string_view as a key in std::unordered_map can be efficient, but it requires careful management of the underlying string's lifetime.

Ensure the data outlasts the map entries to avoid dangling references and undefined behavior. Custom hash and comparison functions are necessary to make this work.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved