1

I use exceptions heavily in my code, so I prefer to use at() rather than find() to find an element, but I just found that at() seems not support std::string_view, for example:

#include <map>
#include <iostream>
std::map<std::string, int, std::less<>> map{
    {"one", 1},
    {"two", 2},
};

const char* c = "onetwothree";

int main() {
  std::string_view s(&c[3], 3);
  std::cout << map.find(s)->second << std::endl;
  std::cout << map.at(s) << std::endl; // will not compile
}

So can I use at() with std::string_view? Or in another word, can at() support heterogeneous lookup?

  • 3
    @Someprogrammerdude I thought a transparent comparator (i.e. `less<>`) was [required](https://stackoverflow.com/a/35525806/7366707) for heterogeneous lookup? (the call to `find` won't compile otherwise, at least.) – Salem Jul 26 '20 at 12:21

1 Answers1

2

Since the C++14 standard the find function have templated overloads that support values equivalent to the keys.

The at function have no such overloads. The value passed to at must be the same type as the key (or implicitly convertible to the type of the key).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 3
    I don't think there's a strong reason for `at` to not support this. It doesn't have to insert anything into the map when the value isn't found (and so doens't have to try and convert a random object type into the key type), so transparent lookup can be made to work. `operator[]` is a no-starter on this, however. I reckon `at` doesn't support it only because it's supposed to be paired with `operator[]` in many ways. – StoryTeller - Unslander Monica Jul 26 '20 at 12:21