简体   繁体   English

加快std :: map和boost:unordered_map []操作

[英]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: 我有一个MAP,它的类型可以是std :: map,也可以是unordered_map类型(根据typdef MAP),还有一个将值添加到给定键值的函数:

  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. 但是上述方法不起作用,因为据我了解,[]运算符使用定义的键和默认double值在map中初始化一个新对象。 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. 如果我知道默认的double值为0,那么func2仍然可以实现我想要的功能-但我不能依靠它。

So is there any way to use [] in a better way over func1? 因此,有什么方法可以比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. 如果找不到该键,则[]将插入一个值初始化的对象(在这种情况下,将是一个值为零的double ),并返回对该对象的引用。 So, in that case map[key] += value has the same effect as map[key] = value . 因此,在这种情况下, map[key] += value具有相同的效果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. 更一般地,它几乎肯定更高效打电话find ,然后检查的结果,而不是调用at和捕获异常。 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. 您无法使用operator[]进行operator[] ,但是可以使用insert方法:它返回迭代器和一个布尔值,指示返回的迭代器是指向先前存在的元素还是指向新插入的元素。

Also, primitive types are default-initialized to zero. 同样,原始类型默认初始化为零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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