加速 std::map 和 boost:unordered_map [] 操作
我有一个 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.
}
}
问题是,这意味着双倍(甚至可能更多) )比简单的工作
func2(MAP<string, double> &map, string &key, double &val2add){
map[key] += val2add; // if map[key] doesn't exist - problem
}
但是上面的方法不起作用,因为据我了解, [] 运算符使用定义的键和默认的双精度值初始化映射中的新对象。如果我知道默认的 double 值是 0,那么 func2 仍然会实现我想要的 - 但我不能依赖它。
那么有没有什么方法可以比 func1 更好地使用 [] 呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的第二段代码没有问题。如果未找到该键,则
[]
将插入一个值初始化的对象(在本例中为值为零的double
),并返回对该对象的引用。因此,在这种情况下,map[key] += value
与map[key] = value
具有相同的效果。更一般地说,调用
find
然后检查结果几乎肯定比调用at
并捕获异常更有效。异常处理实现通常假设异常仅在异常情况下抛出,并以异常情况为代价来优化通常情况。当然,它的速度很重要,那么你需要测量它才能确定。
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, adouble
with value zero), and return a reference to that. So, in that casemap[key] += value
has the same effect asmap[key] = value
.More generally, it's almost certainly more efficient to call
find
and then check the result, than to callat
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.
您不能使用
operator[]
来完成此操作,但可以使用insert
方法:它返回迭代器和一个 bool 值,指示返回的迭代器是否指向先前存在的元素或新插入的元素。此外,基本类型默认初始化为零。
You can't do it with
operator[]
, but you can useinsert
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.