csdude csdude - 3 years ago 245
C++ Question

difference between map_instance[key] vs. map_instance.find(key) in c++

I have a map defined as

static map<unsigned int, deque<FOO_STRUCT*> > CV_MAP;


and I was wondering if one method was better than the other between:

map_instance[key] vs. map_instance.find(key).

Answer Source

map_instance[key] will default construct a new value for the key key if it is not present.

As in, it will call deque<FOO_STRUCT*>'s constructor if key is not present, and return the newly constructed deque<FOO_STRUCT*>.

Using the find member function will not construct a new value for the given key-- when the key is absent, it will just return an iterator that points to CV_MAP.end().

Use what's appropriate for your use case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download