I have read different articles on web and questions at stackoverflow, but for me it is not clear is there any exclusive case when it is better to use std::map::at to retrieve map element.
According to definition, std::map::at
Returns a reference to the mapped value of the element identified with key k.
If k does not match the key of any element in the container, the function throws an out_of_range exception.
For me only case when it is worth to use std::map::at when you 100% sure that element with particular key exist, otherwise you should consider exception handling.
- Is there any case where
std::map::atconsidered as most efficient and elegant way to do? In what cases you will recommend to usestd::map::at? - Am I right that it is better to use
map::find()when there is a possibility to not have element with such a key? Andmap::find()it is faster and more elegant approach?
if ( map.find("key") != map.end() ) { // found } else { // not found }
p.s
map::operator[] sometimes can be dangerous, because if an element doesn't exist then it will inserts it.
EDITED: links somehow related link 1 link 2 link 3 link 4 link 5 link 6
map.find("key"), then you can use theit.secondto access the value, so then there is no need to useat()or[]at all.std::map::at()was introduced in C++11, and usingstd::map::find()was previously the only option. Well, that andstd::map::count().std::map::at()is when thevalueTypeis not default constructible, which is a requirement bystd::map::operator[]std::map::atwhen you 100% sure that element with particular key exists ...". However, no offense, but should it be "... only case when it is worth to usestd::map::atwhen you are NOT 100% sure that element with particular key exists ...". Because, if you are 100% sure, why wouldn't you use the[]operators? right? Please correct me if I'm mistaken. Thank you!std::map::at()? If possible, could you please give a small example? It would help me a lot in understanding your point better. Thank you!