Andrew
Andrew

Reputation: 1621

C++ - How to avoid lookup of map entry after replace using [] operator?

How do I prevent having to call .find() on a map after replacing an element in it using the [] operator? (A little background: I am working on a high performance application and in a critical part of the code.) Example:

m_Map[key] = value;

... // at this point, I need a reference to the m_Map[key] entry, but I don't want to call the .find() method to get to it.

Upvotes: 1

Views: 166

Answers (4)

Tony Delroy
Tony Delroy

Reputation: 106096

There's no particular need to separate capturing a reference from the assignment... can be a one-liner unless you find it confusing or think others might:

value_type& ref = m_Map[key] = value;

Upvotes: 2

Dietmar Kühl
Dietmar Kühl

Reputation: 153820

Just keep a reference to the object you just inserted:

T& reference = map[key];
reference = value;

If you are working on a high performance application you probably don't want to use operator[]() anyway as it first default constructs and object (and probably you don't want to use std::map<...>, either, but rather std::unordered_map<...>). Instead, you'd emplace() the object and keep the iterator return from this operation, e.g.:

std::unordered_map<K, V>::iterator it = map.emplace(key, value).first;
it->second = other_value;

Upvotes: 1

Marco A.
Marco A.

Reputation: 43662

Since the [] operator returns a reference and even iterators are not invalidated, you can simply get away with

auto& element = m_Map[key];
element = value;
// use element

Second choice: you might use the returned iterator from insert (best choice if you need to check if the element existed or not)

Upvotes: 1

AnT stands with Russia
AnT stands with Russia

Reputation: 320421

Instead of assigning directly to the result of [] operator, store the reference first

 DataType &data = m_Map[key];
 data = value;

 // Continue to use `data` here

Upvotes: 3

Related Questions