lundi 14 mai 2018

Index to unordered map via tuple of data heavy objects

I have an std::unordered_map<std::tuple<A, A>, B> map;. I have a function that modifies such map

void modify(const A& a1, const A& a2)
{
    map[/* a1, a2 */].modify();
}

Now I am a bit concerned about unnecessary copies of A's. Here are my attempts.

map[{a1, a2}].modify();

It looks clean, but it constructs temporary key (tuple) from copies of a1, a2.

map[std::tie(a1, a2)].modify();

This looks promising, because it constructs std::tuple<const A&, const A&> and passes that to map's operator[]. Signature of operator[] for my map is

B& operator[](const std::tuple<A, A>&)
B& operator[](std::tuple<A, A>&&)

Which doesn't match return type of std::tie, but it worked. So I look at a constructors of std::tuple and found converting constructors, which made me think, that copies are still made (so I tested it).

Is there a way to query the map, without any unnecessary copies, and still preserve O(1) average lookup complexity?

Aucun commentaire:

Enregistrer un commentaire