[英]std::map: is find(key)->second faster than the [] operator?
std::map<long, double> x;
x[5] = 1.2;
double y = x[5];
double z = x.find(5)->second;
這兩個任務中的一個會比另一個執行得更快嗎? (假設所請求的密鑰始終存在於映射中)在執行x.find(5)->second
時,是否存在與迭代器的解除引用相關聯的開銷?
編輯:謝謝你的回復。 在我的特定函數中,現在我知道它不慢,我可能會使用x.find(5)->second
因為我需要標記我的函數const
(map是一個成員變量)和[]
運算符顯然不允許這樣做(因為它可能會修改地圖是缺少一個鍵)。
這不能解答您的問題,但我會指出您使用find
的方式存在一些問題。
double y = x[5];
double z = x.find(5)->second;
我不能評論哪個更快。 但我可以肯定地說第一種方法是安全的!
如果地圖不包含給定密鑰怎么辦?
在第一種方法中,它將使用給定鍵 創建一個新pair
,並使用默認值double
(即零)初始化該值 ,並將其返回。
但第二個方法呢? 如果在容器中找不到指定的鍵,則find
將返回map::end
,並且您將其取消引用它。 程序崩潰!
使用find
的正確方法是:
std::map<long, double>::iterator it;
if ( (it = x.find(key)) != x.end() )
{
double value = it->second;
}
直接從<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);
}
它看起來大致相同。 應該有什么區別:
iterator _Where = this->lower_bound(_Keyval);
return ((*_Where).second);
和
iterator i = x.find(5);
double d = (*i).second;
我不這么認為。
使用operator[]
的第一個賦值必須執行相同的解引用來檢索find()->second
顯式的值。 您可以確定配置文件,但性能應該足夠接近,您應該使用代碼中最清晰的表單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.