std::map<long, double> x;
x[5] = 1.2;
double y = x[5];
double z = x.find(5)->second;
Run Code Online (Sandbox Code Playgroud)
这两个任务中的一个会比另一个执行得更快吗?(假设请求的密钥始终存在于映射中)在执行时是否存在与解除迭代器的解除引用相关联的开销x.find(5)->second?
编辑:谢谢你的回复.在我的特定功能中,现在我知道它并不慢,我可能会继续,x.find(5)->second因为我需要标记我的功能const(地图是一个成员变量),[]操作员显然不允许这样做(因为它可能会修改地图是缺少一把钥匙).
Naw*_*waz 12
这不能回答你的问题,但我会指出你使用方式的一些问题find.
double y = x[5];
double z = x.find(5)->second;
Run Code Online (Sandbox Code Playgroud)
我不能评论哪个更快.但我可以肯定地说第一种方法是安全的!
如果地图不包含给定密钥怎么办?
在第一种方法中,它将使用给定键创建一个new ,并使用默认值(为零)初始化该值,并返回它.pairdouble
但第二个方法呢?如果在容器中找不到指定的键,find则会返回map::end,并且您将其取消引用它.程序崩溃!
正确的使用方法find是:
std::map<long, double>::iterator it;
if ( (it = x.find(key)) != x.end() )
{
double value = it->second;
}
Run Code Online (Sandbox Code Playgroud)
直接来自<map>:
mapped_type& operator[](const key_type& _Keyval)
{ // find element matching _Keyval or insert with default mapped
iterator _Where = this->lower_bound(_Keyval);
if (_Where == this->end()
|| this->comp(_Keyval, this->_Key(_Where._Mynode())))
_Where = this->insert(_Where,
value_type(_Keyval, mapped_type()));
return ((*_Where).second);
}
iterator find(const key_type& _Keyval)
{ // find an element in mutable sequence that matches _Keyval
iterator _Where = lower_bound(_Keyval);
return (_Where == end()
|| _DEBUG_LT_PRED(this->comp,
_Keyval, _Key(_Where._Mynode()))
? end() : _Where);
}
Run Code Online (Sandbox Code Playgroud)
它看起来大致相同.应该有什么区别:
iterator _Where = this->lower_bound(_Keyval);
return ((*_Where).second);
Run Code Online (Sandbox Code Playgroud)
和
iterator i = x.find(5);
double d = (*i).second;
Run Code Online (Sandbox Code Playgroud)
我不这么认为.
| 归档时间: |
|
| 查看次数: |
14842 次 |
| 最近记录: |