I’m using Google’s sparsehashmap, and trying to work out if a value was inserted or looked up. The following works, but obviously it’s looking it up twice. How do I do it without the double lookup?
Element newElement = Element();
bool inserted = ((*map).insert(pair<const int64, Element>(key, newElement))).second;
Element element = (*(((*map).insert(pair<const int64, Element>(key, newElement))).first)).second;
if (inserted)
puts("INSERTED");
I can’t check the contents of Element (it’s a struct) as I want to differentiate between a default Element being found and newElement being inserted. I couldn’t work out how to assign ((*map).insert(pair<const int64, Element>(key, newElement))) to a variable as it’s of a template type that includes types private to the sparse_hash_map class.
Try this:
If, for whatever reason you don’t like the
std::make_pairfunction, you should consider a typedef for the pair type:Anyway, the return type of
insertispair<iterator, bool>, and AFAIKiteratoris a public typedef of the class.BTW, I don’t get why you do the second
insert… to get to the inserted element? Probably you should declareelementas a reference. In my suggested code:Naturally, if you were using C++11, you could simply do: