1

Consider the two following snippets:

bool foo(const int &lhs, const int &rhs)
{
    const std::map<int, int> bar{{1, 2}, {2, 1}, {3, 3}};

    return bar.at(lhs) < bar.at(rhs);
}

and:

bool foo(const int &lhs, const int &rhs)
{
    std::map<int, int> bar{{1, 2}, {2, 1}, {3, 3}};

    return bar[lhs] < bar[rhs];
}

My questions:

  • In the first snippet, is there a faster const function than at() that will not preform bound-checking?
  • Which is better (faster, more idiomatic), for calling once and many times?
  • 1
    Does this answer your question? [When I should use std::map::at to retrieve map element](https://stackoverflow.com/questions/33236038/when-i-should-use-stdmapat-to-retrieve-map-element) – Passerby Nov 06 '21 at 07:00
  • `Will the at() function stills perform bounds-checking even when bar is const?` Why would you ever assume otherwise? Anyway, yes. `What is better` What is used to measure "better"? How is "better" defined? – KamilCuk Nov 06 '21 at 07:35
  • 1
    "Better" is a relative term. Now generally using `const` will allow the compiler to further optimize as you have guaranteed the values will not change. However, in this case there likely isn't much to be gained. So which is better? Neither really, it is more a matter of what you want the code to be. – David C. Rankin Nov 06 '21 at 07:44
  • 1
    If the map is constant, you assume that the expected key is present, therefore `at` is a better choice since it throws if the key is not present. `operator[]` inserts the key if the key is not present, therefore it cannot be used with a constant map. What’s better depends on your use case. Speed wise `at` might be faster since it does not insert the key if it is not found. – zdf Nov 06 '21 at 07:49

0 Answers0