Why do people use at() to get an item out of a std::map? Why don’t they use the [] operator like in other languages? The documentation on cppreference.com says something mystical like this:
“.. performing an insertion if such key does not already exist.” Why? Well, because it is meant to be used like this:
auto pictures = std::map<uint32_t, std::shared_ptr<PictureData>>;
..
auto& picture = pictures[10];
if (!picture) {
picture = std::make_shared<PictureData>("Picasso", "Las señoritas de Avignon", 1907);
}
If there is nothing on position 10, it creates a default one. PictureData has to be default constructible.
You can use at() instead, it will throw you an exception when you try to access outside of its boundaries.
at()
When using the at() function, if the index is out of bounds, the function will throw an out_of_range exception. This can help catch potential bugs and improve the safety of the code. On the other hand, when using the operator[] method, if the index is out of bounds, undefined behavior can occur, which can lead to difficult-to-debug errors.
operator[]
In general, the operator[] method is slightly faster than the at() function because it does not perform the bounds checking, but the difference in performance is usually negligible. Furthermore, the performance benefit of using operator[] is only significant when the code is run in a tight loop or with very large data structures.
Which one should I choose?
When it comes to choosing between the operator[] and at() functions, it ultimately depends on the specific needs of the application. If safety and reliability are paramount, then the at() function with its built-in bounds checking is the best choice. However, if performance is a top priority, and the code is carefully written to ensure index safety, then the operator[] function can provide a significant speed advantage.