简体   繁体   中英

speeding up std::map and boost:unordered_map [] operation

I have a MAP which is optionally of type std::map and optionally of type unordered_map ( according to typdef MAP) , and a function which adds a value to the given keyed value:

  func1(MAP<string,  double>  &map, string  &key, double &val2add){
    try
{
      map.at(key)  += val2add;
}catch(out_of_range& oor){
          map[key] = val2add; // in case map[key] didn't exist before. 
    }
  }

The problem is that this means double ( and possibly even more ) work than simply

  func2(MAP<string,  double>  &map, string  &key, double &val2add){
       map[key] += val2add; // if map[key] doesn't exist - problem
  }

But the above would not work, since as i understand the [] operator initializes a new object in map with the defined key, and with the default double value. If i knew that the default double value is 0, then func2 would still achieve what i want it to - but i can't rely on that.

So is there any way to use [] in a better way over func1?

There is no problem with your second piece of code. If the key is not found, then [] will insert a value-initialised object (in this case, a double with value zero), and return a reference to that. So, in that case map[key] += value has the same effect as map[key] = value .

More generally, it's almost certainly more efficient to call find and then check the result, than to call at and catch the exception. Exception handling implementations often assume that exceptions are only thrown in exceptional circumstances, and optimise the usual case at the cost of the unusual.

Of course, it speed is important, then you'll need to measure it to be sure.

You can't do it with operator[] , but you can use insert method: it returns the iterator and a bool indicating whether the returned iterator points to a previously existing element or a newly inserted element.

Also, primitive types are default-initialized to zero.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM