Contrary to most existing answers here, note that there are actually 4 methods related to finding an element in a map (ignoring lower_bound, upper_bound and equal_range, which are less precise):
operator[]only exist in non-const version, as noted it will create the element if it does not existat(), introduced in C++11, returns a reference to the element if it exists and throws an exception otherwisefind()returns an iterator to the element if it exists or an iterator tomap::end()if it does notcount()returns the number of such elements, in amap, this is 0 or 1
Now that the semantics are clear, let us review when to use which:
- if you only wish to know whether an element is present in the
map(or not), then usecount(). - if you wish to access the element, and it shall be in the
map, then useat(). - if you wish to access the element, and do not know whether it is in the
mapor not, then usefind(); do not forget to check that the resulting iterator is not equal to the result ofend(). - finally, if you wish to access the element if it exists or create it (and access it) if it does not, use
operator[]; if you do not wish to call the type default constructor to create it, then use eitherinsertoremplaceappropriately