4

When I want get certain element from a std::map, as far as I know at() will do a bounds check. Does that mean it's slower than []?

3
  • 3
    No, it is not slower. The only difference is, it does not create new element but throws an exception if an element does not exits. Commented May 27, 2020 at 3:35
  • @ S.M. Thanks,no wonder I google so many times,and none of those reference say that ".at" is more slow Commented May 27, 2020 at 3:48
  • 4
    For a lot of containers with [] support it is slower because of the bounds check, but map has very different behaviour. Commented May 27, 2020 at 4:07

1 Answer 1

4

Both std::map::at and std::map::operator[] check for the presence of a key. The former throws an exception when not found, the latter creates a default value.

Their complexity is mandatory to be log(n) (look-up). Performance by itself is not mandatory to be identical, but should be similar in practice.

So choose the one to use from their behavior (after the look-up). Similar alternatives might be map::find or in some cases map::insert/insert_or_assign/emplace.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.